Harry Karanja
Harry Karanja

Reputation: 1

Session variables lost after header redirect

Bear with me if this looks similar to other questions posted here, I have already gone through all answers provided but not has solved my problem. I've reduced my problem to the bare minimum.

  1. I have two pages (page1.php, page2.php)
  2. Page1.php creates a session variable and if the session variable is set it then sends the browser to Page2.php
  3. On page2.php the browser is supposed to display the value of the session variable set in Page1. php
  4. My problem is that page2.php views the session variable as not set.
  5. I have tried all the solutions posted by other users on stack overflow as you can see from my code below:

Page1.php

<?php
//start the session
session_start();

//set the session
$_SESSION['mysession'] = "Hello";


if(isset($_SESSION['mysession'])){
    //redirect the person to page 2
    session_write_close();
    header("Location: page2.php?PHPSESSID=".session_id());
    exit();
} else {
 echo "Session Not Set";
}
?>

Page2.php


<?php
//start the session
session_start();
session_id($_GET['PHPSESSID']);

if ( isset ($_SESSION['mysession']) )
   echo $_SESSION['mysession'];
else
   echo "Session not set!";
?>

Upvotes: 0

Views: 8076

Answers (2)

worenga
worenga

Reputation: 5856

session_id() needs to be called before session_start()

If id is specified, it will replace the current session id. session_id() needs to be called before session_start() for that purpose. Depending on the session handler, not all characters are allowed within the session id. For example, the file session handler only allows characters in the range a-z A-Z 0-9 , (comma) and - (minus)!

Note: When using session cookies, specifying an id for session_id() will always send a new cookie when session_start() is called, regardless if the current session id is identical to the one being set.

session_id()-Manual

You've also might check whether you'll have cookie based authentication set.

Be aware that if users post the url, they might carry the session to another client.

Upvotes: 3

web-nomad
web-nomad

Reputation: 6003

On page2.php, interchange the first 2 lines. Change

session_start();
session_id($_GET['PHPSESSID']);

to

session_id($_GET['PHPSESSID']);
session_start();

See the Parameters section here..http://php.net/manual/en/function.session-id.php

Upvotes: 1

Related Questions