Solved

Another header question by a PHP newbie

Posted on 2004-09-13
12
279 Views
Last Modified: 2008-02-01
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.
0
Comment
Question by:nicky2k
  • 6
  • 5
12 Comments
 
LVL 48

Expert Comment

by:hernst42
ID: 12048069
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
 
LVL 3

Expert Comment

by:steve918
ID: 12048090
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
 

Author Comment

by:nicky2k
ID: 12048262
Now I've got rid of the message, but I get redirected all the time to the login page!!!
0
 
LVL 48

Accepted Solution

by:
hernst42 earned 150 total points
ID: 12048287
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
 

Author Comment

by:nicky2k
ID: 12048354
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
 
LVL 48

Expert Comment

by:hernst42
ID: 12048376
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:nicky2k
ID: 12048470
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
 
LVL 48

Expert Comment

by:hernst42
ID: 12048545
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
 

Author Comment

by:nicky2k
ID: 12049051
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
 
LVL 48

Expert Comment

by:hernst42
ID: 12049298
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
 

Author Comment

by:nicky2k
ID: 12052856
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
 

Author Comment

by:nicky2k
ID: 12052919
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

Featured Post

Easy Project Management (No User Manual Required)

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
This article discusses how to create an extensible mechanism for linked drop downs.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now