Another header question by a PHP newbie

I want to re-direct users to the log in page if not logged in using the code
//session_start();

ob_start()

if (!$_SESSION["userid"])
{
// User not logged in, redirect to login page
Header("Location: login.php");
ob_flush();
}

I keep getting the following:
Warning: Cannot modify header information - headers already sent by (output started at <page name>)

Also, if I uncomment the session line, I also get
Warning: session_start(): Cannot send session cookie - headers already sent by (output started at <page name>

How can I correct this? Thanks.
nicky2kWeb DeveloperAsked:
Who is Participating?
 
hernst42Connect With a Mentor Commented:
If that warning comes for session_start() there has been made output before that function is executed by PHP. Instead of using ob_flush() you might use
ob_end_clean();
die(1);

The interessting part (the lines before //session_start(); or the first lines of your php-script) are missing so we could see where that error might come from. If you have firther problems please post that lines.
0
 
hernst42Commented:
There is other output send by your script. maybe
<newline>
<?php
// your script

put at the 1st line of your script  (before you incude anything or call any function)
<?php ob_start();?>

Then you should be able to get rid of that messages ans session_start() should also work
0
 
steve918Commented:
sometimes ob_flush sends headers when it shouldn't especially with Apache 2.  You might try

header("Location: login.php");
exit;  // Try adding exit

If that don't work try removing ob_flush and make sure you don't have any characters INCLUDING blank space after the ?>
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
nicky2kWeb DeveloperAuthor Commented:
Now I've got rid of the message, but I get redirected all the time to the login page!!!
0
 
nicky2kWeb DeveloperAuthor Commented:
Now I have

<?php
 ob_start();

session_start();

if (!$_SESSION["userid"])
{

// User not logged in, redirect to login page
Header("Location: login.php");
ob_end_clean();
die(1);

The header error has gone, but the session error remains. I read in a PHP text book that session_start(); has to be written on every page where sesssion variables are used. Is that true?
0
 
hernst42Commented:
Is session_start still commented out ? and is $_SESSION["userid"] realy set.

Change:
if (!$_SESSION["userid"]){
// User not logged in, redirect to login page
Header("Location: login.php");

to:

if (!$_SESSION["userid"]){
// User not logged in, redirect to login page
var_dump($_SESSION);
die(1);

so you will see whats in your session, but you won't be redirected.
0
 
nicky2kWeb DeveloperAuthor Commented:
With session_start(); commented out, i get NULL in the browser.
$_SESSION["userid"] was supposed to be set during the login process below:-

<?php
      session_start();
      
      ob_start();

             
      
      // dBase file
      include "dbConfig.php";
      
      if ($_GET["act"] == "login")
            {
            if (!$_POST["username"] || !$_POST["password"])
                  {
                  die("You need to supply a username and password.");
                  }
            
            // Create query
            $q = "SELECT * FROM  users WHERE username='".$_POST["username"]."' AND password='".$_POST["password"]."'";
                  
            echo $q."<br><br>";
            
            // Run query
            $r = mysql_query($q);

            if ( $obj = @mysql_fetch_array($r) )
                  {
                  // Login O.K., create session variables
                  $_SESSION["userid"] = $obj["userid"];
                  $_SESSION["loggedinuser"] = $obj["first_name"]."&nbsp;".$obj["last_name"];
                  $_SESSION["usertype"] = $obj["usertypeid"];
                  $_SESSION["sitename"] = "Elephantfeet.com website administration";
                  $_SESSIOM["imagepath"]= "C:\Inetpub\wwwroot\elephantfeet\generic_images";
                  $_SESSION["valid_time"] = time();

                  // Redirect to member page
                  
                  Header("Location: admin_main.php");
                  ob_flush();
                  }
            else
                  {
                  // Login not successful
                  die("Sorry, could not log you in. Wrong login information.");
                  }
            }
      else
            {
      ?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
      <TITLE>Elephantfeet.com website administration</TITLE>
      <META NAME="Generator" CONTENT="TextPad 4.4">
      <META NAME="Author" CONTENT="?">
      <META NAME="Keywords" CONTENT="?">
      <META NAME="Description" CONTENT="?">
      <LINK REL="stylesheet" href="styles/sitewide.css">
      <script language="JavaScript" src="scripts/loginval.js"></script>
</HEAD>

<BODY BGCOLOR="#FFDD66" TEXT="#000000" LINK="#FF0000" VLINK="#800000" ALINK="#FF00FF" BACKGROUND="">

<table width="800" height="600" cellpadding="0" border="0" cellspacing="0" align="center">
      <!-- Header Row 2cx1r -->
      <? include("includes/header.php") ?>
      <tr>
            <td>&nbsp;</td><!-- Spacer Row -->
      </tr>
      <!--- menu row ---><?php  echo $_SERVER["server_name"]; ?>
      <tr>
            <td align="left"  valign="top">
                  <form action="login.php?act=login" method="post" name="loginform">
                  <table cellpadding="4" border="0" cellspacing="0" width="100%" align="left">
                        <tr>
                              <td align="center" colspan="2"><h2>Log in</h2></td>
                        </tr>
                        <tr>
                              <td align="right" width="50%">Username :</td>
                              <td align="left" width="50%"><input type="text" name="username" size="20" maxlength="50" class="input"></td>
                        </tr>
                        <tr>
                              <td align="right" width="50%">Password :</td>
                              <td align="left" width="50%"><input type="password" name="password" size="20" maxlength="50" class="input"></td>
                        </tr>
                        <tr>
                              <td align="right" width="50%"><input type="submit" name="submit" value="Log in" class="button" onclick="return loginval();"></td>
                              <td align="left" width="50%"><input type="reset" value="Clear" class="button"></td>
                        </tr>
                  </table>
                  </form>
            </tD>
      </tr>
      <? include("includes/footer.php") ?>
</table>
</body>
</html>

<?php

}

?>

0
 
hernst42Commented:
If you don't use session_start on that page then the $_SESSION variable is null/empty and that check
if (!$_SESSION["userid"]) will always be true and you will be redirected. So so not comment out session_start();
0
 
nicky2kWeb DeveloperAuthor Commented:
Uncommented, I still get
Warning: session_start(): Cannot send session cookie - headers already sent by (output started at <page name>), but the value of $_SESSION["userid"] is now displayed.
0
 
hernst42Commented:
Is that file included into another page ? whcih might have printed something:

If you file loks like the following and is not included from another page so this code may not produce such an error:
<?php
ob_start();
session_start();
if (!$_SESSION["userid"])
{
...
0
 
nicky2kWeb DeveloperAuthor Commented:
The login process does everything on the same page and sets the session variables. I then want to use these session variables throughout the application until the session expires, hence the test for $_SESSION["userid"]. The code I have is EXACTLY as you have written it.

The process should be
1) Enter username and password into login form, which posts to itself
2) When form details are posted, check database to see if user exists. If user exists, set session variables and then take user to main home page (NOTE: redirection done hear also, which is ehre header may have been printed), Else let user view log in form again.

I will try adding ob_end_clean(); die(1); in the log in page. if it works, you get the points!!!

:)

0
 
nicky2kWeb DeveloperAuthor Commented:
I have ob_start(); on every page!!!! That is what the problem was!!! What do you know, you live and learn!!
But hernst42, you get points for putting up with me.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.