Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

php - 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!";
?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...