PHP and the Amazing Invisible Session

29th August, 2005 @ 5:13pm BST

Development, PHP / 2 Comments

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!

Like this post? Digg it, Del.icio.us it, Ma.gnolia it!

Comments (2)

Skip to the comment form…

  1. Gravatar Image Andrew August 30, 2005 @ 11:08 am

    Excellenty :) Had this a number of times, seemed really inconsistent. Ended up using a META refresh with an annoying “you are being forwarded” page.

  2. Gravatar Image Tim August 30, 2005 @ 11:20 am

    Yeah - I’ve either had to do that or die to a javascript refresh (which is equally nasty!)

    In this particular instance, I had the option of not refreshing but it meant if the user refreshed the page, they would get that nasty “Resend Post Variables?” message…

Leave a comment





Categories

Syndication

Technorati

© 2008 Tim Huegdon, All Rights Reserved / Website design and development by Nefarious Designs

Powered by Wordpress 2.3 / Login

Not suitable for children over the age of 6.