php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #14636 Session variables are lost when redirecting to a url using header() function.
Submitted: 2001-12-21 03:12 UTC Modified: 2010-09-29 17:30 UTC
Votes:5
Avg. Score:3.6 ± 1.5
Reproduced:4 of 4 (100.0%)
Same Version:2 (50.0%)
Same OS:1 (25.0%)
From: kannan at tmsassociates dot com Assigned:
Status: Not a bug Package: Session related
PHP Version: 4.0.6 OS: windows 2000 professional
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: kannan at tmsassociates dot com
New email:
PHP Version: OS:

 

 [2001-12-21 03:12 UTC] kannan at tmsassociates dot com
I have 2 scripts: a script to login a user and set a session variable.  After checking session_is_registered() I redirect to a url using header().  The target script checks for the session variable and is not able to find it.

If I use href to go to the target page, the session variable is found.

I have reviewed the bugs database, and the solutions reported for similar cases do not work for me.  The following are portion of the code used:

I tested the code on a Linux server and it works perfectly.
Thank you.
Kannan

Environment:  Windows 2000, IE 5.5, Linux 4.0.6

Login.php>>
  $db = db_connect();
  $result = mysql_query($query, $db);
  if (mysql_num_rows($result) >0 )
  {
    // if they are in the database register the user id
    $row = mysql_fetch_array($result);
    $suser = $user;
    session_register("suser");
  }
}

if (session_is_registered("suser"))
  {
    if ($redirect<>"")
      header("location: $redirect"); 
    // redirect is instantiated with 'members_only.php'
    else {
         echo "You are logged in as: $suser <br>";
	 echo "suser: $suser<br>";
	 echo "<a href=\"members_only.php\">Members Only</a><br>";
	 echo "<a href=\"logout.php\">Log out</a><br>";  //  ======= redirect to URL ====
			}
  } 
.....

members_only.php>>
<?
  session_start();
  // check session variable
  echo "Members_only<br>";
  echo "$suser<br>";
  if (session_is_registered("suser"))
  {
    echo "Members Only Page<br>";
    echo "<p>You are logged in as $suser.</p>";
    echo "<p>Members only content goes here</p>";
    echo "<a href=\"login.php\">Back to main page</a>";
    echo "<a href=\"logout.php\">Logout</a>";
  }
  else
  {   $redirect = "members_only.php";
      header("location: login.php?redirect=$redirect");
  }

?>

php.ini>>
[Session]
session.save_handler = files
session.save_path = C:\temp
session.use_cookies = 1
session.name = FOO
session.auto_start = 1
session.cookie_lifetime = 60
session.cookie_path = c:\temp
session.cookie_domain = 
session.serialize_handler = php
session.gc_probability = 1
session.gc_maxlifetime = 1440
session.referer_check =
session.entropy_length = 0
session.entropy_file =
session.cache_limiter = private
session.cache_expire = 180
session.use_trans_sid = 1
url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=fakeentry"

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2001-12-21 08:36 UTC] kannan at tmsassociates dot com
I have reviewed the Bugs database against the following IDs

13732 - is closed with no reply or resolution indicated.
12704 - marked Bogus
12679 - does not solve my situation  (session.cookie_domain).  I am not using one.  It is left blank.
8912 - similar.  But in my case browser refresh on the target page also does not solve the problem.

The only thin that works is clicking on a href link to go to the target page.

I am using Apache Webserver 1.3.22 for Windows.

Kannan

 [2001-12-21 08:52 UTC] sander@php.net
Dupe of 6121
 [2001-12-21 12:19 UTC] kannan at tmsassociates dot com
The problem as I understand it is in the use of 

session.auto_start in the php.ini and
session_start() in the script.

session.auto_start has to be set to 0 (zero) if using session_start() in the script.  The code seems to work with this setting.  Somehow I did not see this in any of the documentation or other bug reports.

Thanks for the assistance.
Kannan
 [2001-12-21 20:35 UTC] yohgaki@php.net
Let me check this thing ;)
 [2002-02-03 22:32 UTC] chris at k2labs dot org
This is actually not a bug at all but rather behavior of HTTP.

For PHP to be able to "find" a previously set session variable, it must be able to identify the client, right? Well, the default method used to accomplish this is via a cookie set when you initiate the session. Since it appears you are redirecting the user to the member's only page using the Location header on the same page the session is initiated, the PHPSESSID cookie will not be set. Thus, once the user arrives at the member's only page, PHP won't be able to identify the user. Their session variable is still there, but PHP won't give it to a stranger. :)

Basically, in your HTTP reponse that includes the Set-Cookie header, it needs to be a regular 200 OK response and not a protocol level redirection. If you absolutely have to have the behavior you're going for here, you're going to have to use a meta refresh for the redirection. Yes, it's not as cool, but it's the only way to set a cookie and redirect the client in the same response. Otherwise, you'll have to pass the value of the cookie on the URL, which might be a good option for you actually.

Hope that helps.
 [2002-02-04 00:51 UTC] yohgaki@php.net
I'm not sure what is going on, since I didn't have time to take a look.
To report: Is chris' comment enough?
 [2002-02-07 05:25 UTC] betsos at westgate dot gr
I have experienced a similar problem with Kannan but not 
due to session.auto_start. In my php.ini session.auto_start 
is set to 0.

I use the following scripts. When run, either with PHP Version 4.0.6, or with Version 4.1.1 and IIS under NT 4.0,
the second script  - test_login.php - starts a new session
and variable $username is unset. When run with PHP 4.0.1
and Apache under Unix they work just fine.

// ------ login.php ------

<?php 

session_start();
session_register("username");
		
$username = "justme";
			
Header("Location: ./test_login.php");

?>

// ------ test_login.php ------

<?php 

session_start();
	
if ( isset ($username) )
   echo $username;
else
   echo "Not authenticated!";
?>

// -----------------------

According to Chris 'This is actually not a bug at all but rather behavior of HTTP'. 

If this is the case then how comes that I don't have this
problem when I use PHP Version 4.0.1 with Apache?
 [2002-02-07 21:23 UTC] yohgaki@php.net
This issue will not be able to be fixed by PHP.
Some browser does not set cookie for initial request.

To make sure cookie is enabled _always_, user must check it first.

http://www.zend.com/search_code_author.php?author=yohgaki

Use session helper html or other people post without JavaScript version.
 [2003-11-22 18:18 UTC] andrew dot whale at which dot net
Hi

I've also had a similar problem of session variables not being passed following a call to header(). I am running PHP 4.0.15 on an XP m/c.

The following worked for me, by placing a session_write_close() before the call to header, followed by and exit():

	session_write_close();
	header("Location: $strPage");
	exit();

I hope this will be of use to some.
Andrew Whale
 [2003-12-05 23:28 UTC] venki_cute123 at rediffmail dot com
i have a session variable to be accessed in same page but submit twice in same page at third time I am not able to access session variable
 [2004-01-09 17:47 UTC] writeto_ben at hotmail dot com
I would have liked a simple header redirect as well, but unfortunately the other suggestions didn't solve the issue. However, setting a javascript redirect seemed to do the trick. I'm using Win2k professional, IIS 5.0, PHP Version 4.3.4

This will work on IE browsers. Just modify the javascript for netscape compatibility.

<?
//...perform login check, produce $errStr if fails

if($errStr){
    header("Location: login.php?err=".$errStr);
}else{
    print '<html>
             <body onload=eval("window.location.href=\'http://blahblahblah/default.php\';");></body>
          </html>';
}
?>
 [2004-01-13 15:34 UTC] mgandalf at seznam dot cz
Hi, I just look at your source and php.ini and it was clear
to me. Problem is here: "session.cookie_path = c:\temp".
It is not path to file but path on web server where is
cookie valid. So change it to "session.cookie_path = /"
and it will work. When it is for example "/dir_name",
cookie is valid just for http://server/dir_name/, but not 
for http://server/dir_name2/ and in this 2nd case will not be sent. Gandalf
 [2004-01-23 01:53 UTC] moon_wizard at yahoo dot coom
I just ran into the same issue.  I set up PHP and Apache on my home Windows machine.  I was able to successfully set SESSION variables and recover after a header() call.

When I moved the file to my hosting provider, the SESSION variables were lost.  I think that my hosting provider might be using IIS.

I tried the session_write_close() with no success.

John Gregory
 [2004-01-29 06:53 UTC] brett dot crosby at australiswebtech dot com dot au
Have experienced the same problem where an application works fine on LAMP and not on Win2k. One thing that I did notice (by accident - I turned on debugging to see what was happening) is that if I send some output to the second page prior to the header() command the session variable was registered. I'm then able to shut down the browser and restart without problems. However, if I reboot my machine, I must send the debug output again.
Note to self: Perhaps there is a way of sending some data to the browser that will instantiate the session but clear the buffer before sending the 'real' data?
 [2004-02-15 19:15 UTC] smcbride at msn dot com
I have had the same problem on Windows/IIS.  I thought it was a coding mistake, but it turns out to be a problem with PHP / IIS.  When running php as a cgi exe, it does not set up the session properly the first time.  If you run it as an ISAPI extension, it works.  I spent a few hours on this one.  If your symptoms are that the first time it does not work and then hit the back button in the browser and try again and it works, then it is probably this.  I read somewhere that this is actually a IIS issue.
 [2004-02-21 18:50 UTC] michael at graber dot org
Just found an annoying quirk (aka bug) in IE - after applying a security patch, IE no longer sets cookies if the server or domain name contain anything except alphanumerics (ie, no "_" or "-", etc.).

The symptom was that every page or refresh of the same page generated a new session, and obviously no variables were passed from page to page.

http://support.microsoft.com/default.aspx?scid=kb;EN-US;316112
 [2004-04-13 18:58 UTC] fvincentis at yahoo dot com
Had the same problem on IIS with the php cgi. The session_write_close() did it for me! It didn't write the session variables before, but now they are stored even if a header redirect follows.
 [2004-05-23 21:02 UTC] lorenzob at interia dot pl
I'm working on PHP 4.2.3 with Apache 1.3.9 and I've got the problem mentioned above. After logging in I do the simple

session_start()
$_SESSION['user'] = $_POST['login']

and as for that everythings fine. But when changing from test.php, where above code is stored, into another page klient.php during the same session the variable appears to be empty! In short, although the variable is being registered fine it's not visible in other scripts, what is an obvious denial of an idea of session variables.

Can anyone help? I've been fighting this one for over three days in many ways but nothing seems to have an effect.

test.php:

     session_start();
     header("Cache-control: private");
     ob_end_flush();
     session_register("log");
     session_register("pas");
     $log = $_POST["login"];
     $pas = $_POST["pass"];

klient.php:

    session_start();
    header("Cache-control: private");
    ob_end_flush();

    $im = $log;
    $naz = $pas;
    echo "->".$im;

Big thanks in advance
 [2004-07-16 06:30 UTC] anonymous at anonymous dot com
Yes I have recently seen this phenomenon.
Note that I am purposely NOT saving session data in cookies.

session_start();
$_SESSION["foo"] = "bar";
header( "Location:foobar.php" );

On the remote Unix server running Apache I upload this to, it works fine.  The session data is passed to foobar.php.
However on my local Windows machine, the session data is lost.  I end up having to pass session data in the header myself.

header( "Location:foobar.php?" . Session_Name() . "=" . Session_ID() );

It works but I'd rather not resort to that.
 [2004-08-03 07:38 UTC] venky at netkode dot com
Hi,

I am facing the similar problems with Sessions. I register session variables in the Login page and redirect through header to user area and have one checklogin file which will check the sessionid and some other session values. But here I am not able to get the values. This issue is not occuring very often but out of 500 attempts one or two complaints are coming up. Most of the cases are with I.E 6.0. Any work around will be of great help.
 [2004-08-10 17:49 UTC] mhdskr at yahoo dot com
I faced exactly the same problem : (USING W2K-IIS5/PHP4.3.7)

I take the login username and password and store it in the session and then redirect to another page .. The first time I reach there the session is not set. I hit browser back and re enter the login information it works fine

The first login page contains html only - no php
I start the session in the second page that checks the login and redirect to the third page

MY SOLUTION - it worked for me in this way! :
I added the following to the first (html-only) page :

<?php 
session_start();
?>

Isn't it strange ?!?
 [2004-08-12 10:27 UTC] venky at netkode dot com
Hi,

As i said earlier i have login page which registers session variables and go to the login area where check.php will check for the session variables. Here i compare old session id stored in session variable with session_id(). but here initially stored sessionid and session_id() were not equal. It means browser is generating new id after redirected. Could anyone help me in work around for this.

I am desperately waiting for help over this.
 [2010-09-29 11:26 UTC] derik at igroup dot co dot za
I have exactly the same issue but not in all the browsers. Only Safari and Internet Explorer causes the sessions to disappear. All the other browsers works seamlessly.

I have tried everything mentioned in this thread to try and solve my redirect and AWOL sessions issue but without any luck.

Running a Centos server with latest php and apache installed. I'm thinking of just scraping the sessions idea and do a entry in a tmp table in my db.
 [2010-09-29 17:30 UTC] rasmus@php.net
This issue, as originally reported, was due to an IIS CGI bug described here:

http://support.microsoft.com/kb/q176113/
 [2010-10-18 07:18 UTC] windlaiden at gmail dot com
I have a user session which only works on the localhost. The session value gets 
disappeared when i access over the network. I am doubting whether it is a server 
configuration problem.

Did any one face such a problem? If you have a solution I am very much in need.
 [2011-10-26 17:35 UTC] lukas dot liesis at gmail dot com
this is not a bug!

Just your session vars are lock till all script ends and you cut this by 
redirecting to new location. use this:

http://php.net/manual/en/function.session-write-close.php

best wishes :)

http://free-templats.lt/ - Free Joomla Drupal Wordpress Themes! 10 000+
 [2012-04-26 15:16 UTC] dobryen_dev at internode dot on dot net
For anyone learning session variables like myself, it is worth noting that session_start() not only creates a new session, but it also resumes a current session. I wasn't aware of this when attempting to do a header redirect and I couldn't figure out why the variables weren't accessible on the page directed to (I hadn't placed it in the php block that retrieves the variables).

tl:dr Anyone else learning session variables, try re-reading session_start() in the PHP manual
http://php.net/manual/en/function.session-start.php
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun Nov 24 09:01:31 2024 UTC