PHP session variable still setting AFTER header is sent
index.php
<?php
session_start();
header("Location: somewhere.php");
?>
<html>
<head></head>
<bod开发者_如何学JAVAy>
<?php $_SESSION['foo'] = 'bar'; ?>
</body>
</html>
somewhere.php
<?php
session_start();
echo $_SESSION['foo'];
?>
I set a session variable in the body after a header call in index.php
. Then it's found in somewhere.php
. This happens even after restarting the browser. How is this happening?
Well, why not?
// starts session, sets cookie with session id
session_start();
// outputs Location header
header("Location: somewhere.php");
// rest of code keeps executing!
// sets session value foo
$_SESSION['foo'] = 'bar';
Just because you're outputting a Location
header doesn't mean the rest of the script doesn't execute.
The session value is set and saved on the server, this is completely independent of whether headers have already been sent or not. The only header that needs to be send to the client is a cookie containing the session id, this can happen before or after populating the session values in the server's memory.
EDIT: Erhm. I'm tired. I misunderstood your question. Feel free to ignore this post
Session variables are superglobals. A cookie gets set in the client's browser with a session id. Whatever you set in $_SESSION get's stored on the server linked to the client's session id. When the user browses to a web page, PHP automatically populates $_SESSION with any previous data, until the session has expired.
try this and see if you are getting the same results:
<?php
session_start();
unset($_SESSION['foo']);
header("Location: somewhere.php");
?>
Edit:
<?php
session_start();
unset($_SESSION['foo']);
header("Location: somewhere.php");
exit;//maybe this will stop the script from setting that session
?>
Becuase when you compiler rached on 4th line "header("Location: somewhere.php");"
your control goes to somewhere.php
You can use this.
index.php
< ?php
session_start();
$_SESSION["foo"] = "bar";
header("Location: somewhere.php");
?> Surely It will run
精彩评论