Ben
Ben

Reputation: 57277

PHP session variable still setting AFTER header is sent

index.php

<?php
session_start();
header("Location: somewhere.php");
?>

<html>
  <head></head>

  <body>
  <?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?

Upvotes: 1

Views: 2974

Answers (4)

Jason
Jason

Reputation: 2727

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
    ?>

Upvotes: 1

deceze
deceze

Reputation: 522382

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.

Upvotes: 2

Karandeep Singh
Karandeep Singh

Reputation: 1279

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

Upvotes: 0

rcapote
rcapote

Reputation: 1044

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.

Upvotes: 2

Related Questions