PHP: My session variables are not being saved

Written on

You might have found yourself in the situation where you're building a PHP application and you noticed that your session variables are not getting saved. You've verified that they were set on the first page, but on the second page they aren't there anymore or they have older values.

Why does this happen?

In PHP, session variables are saved automatically once the script terminates. So why aren't they getting saved? When you call the header() function to redirect to another page, the second page may have started loading before the first script finished executing, since the first script hasn't finished the session has not been saved yet. The result being that the values are not present in the session.

How do I fix it?

Since the problem is about the session not being saved, the solution is to save the session before redirecting. How to do that? Use PHP's session_write_close() function. This function saves the session before the script continues running.

session_write_close();
header('http://www.example.com/page2.php');
exit;

Well, that was a simple solution. Happy coding!