Session data not persisting

Follow

Issue

Session data is not persisting.  Session data written by one script is not available for the next script.  This article describes a method to narrow down the possibilities of what may be causing the issue.

Environment

PHP running on any platform.

Resolution

A simple script can sometimes help to get a better definition of the issue. Please create a script, calling it something like session_test.php:

<?php

session_start();

if (empty($_SESSION['count'])) {
   $_SESSION['count'] = 1;
} else {
   $_SESSION['count']++;
}
?>

<p>
Hello visitor, you have seen this page <?php echo $_SESSION['count']; ?> times.
</p>
<p>
The session ID is <?php echo session_id(); ?>.
</p>

The expected result should look something like this in your browser (the session ID will of course be different):

Hello visitor, you have seen this page 1 times.

The session ID is ikiq2rfcqo4ojgm4quvjftocplf8v6sr. 

If that output appears, this file should exist (assuming the session.save_path is set to the default of /tmp):

/tmp/sess_ikiq2rfcqo4ojgm4quvjftocplf8v6sr

Notice that the part after 'sess_' is the session ID.

When you run this script, what happens? Do you see a session ID, or is it blank?

If the session ID is blank, the session is not set. Are files with the prefix 'sess_' being written to /tmp (or the session.save_path directory)? If so, try counting them, run the script once, and count again to see if a new file gets written. If no new files are bring written, it seems most likely this is some permissions issue preventing the file from being written.

If you see a session ID, please try hitting refresh in your browser a few times.

If the count stays at 1, and the session ID does not change, then the $_SESSION['count'] element is not stored. Look for the session file in /tmp. What are the contents? Is it empty?  If the file is not written to, again the most likely culprit is some permissions issue.

If the count stays at 1, and the session ID changes every time, then a new session is set every time. Perhaps your browser is not storing the cookie? Check your browser settings to insure cookies are permitted. Or, maybe you are running the script in the Studio debugger using the internal Studio browser, in which case the cookie is not set. Try using an external browser (Window -> Preferences -> General -> Web Browser -> Use external web browser). Or use the Zend Studio Toolbar in your web browser (available for IE and Firefox) to debug from the browser.

If the count increments and the session ID stays the same, then sessions are working, and the problem you are experiencing is likely something related to your PHP code.

Have more questions? Submit a request

Comments

Powered by Zendesk