PHP Session Data Lost Between [Some] Pages

frustrated

Ugh… So I’ve been working on a website for a student group at the University of Oregon. I’m developing a custom content management system for the site that uses jQuery UI and AJAX. It’s pretty spiffy actually.

Unfortunately I’ve always had problems maintaining $_SESSION data on the University web-server. For some reason my authentication class would work fine on my dev environment, but would randomly lose and then remember the $_SESSION data on the University web-server. This means that administrators would randomly get logged out when they were trying to update the site.

So after getting frustrated and avoiding the problem for several weeks, I finally found a solution here.

It turns out that the session.save_path value in php.ini was not set. The solution was to run session_save_path() at the top of my script and set the path manually to my home directory (one level below public_html).

<?php
  session_save_path('/home5/twadding/session_data/');
?>

This seems to have resolved the problem nicely. One caveat. Don’t keep your session data anywhere that is publicly accessible. Otherwise malicious users could access any of your session data on a whim.

Spending a week pouring over my code was incredibly frustrating, but at least my authentication class is nicely tuned now.

Thanks to turkguy0319 for the great image.

One comment

  1. Hi. Thanks for this!

    I had the same problem and it was very frustrating due to the random and seemingly unpredictable nature of it. Sessions could last anywhere from 20 seconds to 20 minutes.

    However in my case the server DID have a valid setting for save_path (it was simply “/tmp” which is quite a normal setting for linux servers) but I was still getting the random loss of session data. After setting the save_path to a local folder near my own home directory as you suggested, the problem went away.

    So what causes the problem in the first place? It should be quite acceptable to store session data in temporary folders. It could be that the folder was being prematurely cleansed by some other process, but that wouldn’t explain how, as you also mention, the session data would randomly disappear and then sometimes RE-appear! This to me indicates a file access problem, where the file is still there but unable to be read on occasion. I think that when it comes down to it, if the server is hosting a large number of sites, each of which is running potentially a large number of sessions simultaneously, it becomes a bit too much for the system when all of those processes need access to the same folder at the same time.

    It would have been nice if I had received some kind of notification that the session data file could not be read, but hey, perhaps there is a log file somewhere I’m not privy to. It’s not my server after all.

    Enough of my waffling! Thanks again for the tip :)

Leave a Reply