Q:

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?

A:

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.

