PHP and the Amazing Invisible Session

Published 01:13 on 30 August, 2005

Yow. Just discovered the solution to a bug I’ve experienced many times in the past! To be honest, I’m not sure why I haven’t looked for a solution before.

Often, having created a $_SESSION variable in PHP and then redirecting using the header command, you’ll discover your session has somehow disappeared! This is because you’ve technically done a redirect before PHP has worked out you’ve finished with the session. Solution? Tell PHP you’re done with the session using the session_write_close() function like so:


// Set up your session
session_start();
// Write something to it
$_SESSION['myvar'] = 'dave';
// Tell PHP you're done writing to it
session_write_close();
// Redirect
header('Location: mypage.php');

What a doddle!