Session variables not persistent in PHP5/Apache2/Ubuntu12

Diego asked:

I have a website that uses session variables (in PHP) to know if the visitor is entering the website or not. If he’s new, then I redirect him to the detected language. But if he’s not new, you let him go wherever he wants to (even the pages in other languages).

The problem is that the variable used to achieve this ($_SESSION[“knownvisitor”]) is not persistent. I’ve tested the same website in other server and it works just fine, so I’m pretty sure it’s a sessions config problem. The problematic server is an Ubuntu Server 12.04.4 with Apache 2.2.22 and PHP 5.3.10.

The sessions are stored in “/var/lib/php5”, and I can see the files there but they are empty. The session files belong to “www-data” and have the following rights “-rw——-“. The directory, in the other hand, belongs to “root” and has these rights “drwx-wx-wt”.

I tried using “session_write_close()” before redirecting, as recommended in some forums, with no luck. The redirection is like “header(‘Location: [URL]’)”.

Here’s the code of the script so you can understand its basic behavior. This is what I put in the beginning of all the files in my web:

function detectedlang($availlangs)
 return $detectedlang;


if (!isset($_SESSION["knownvisitor"]))
 $detectedlang = detectedlang(array("en", "es"));
 $_SESSION["knownvisitor"] = true;

My answer:

You said that /var/lib/php5/session is owned by root and has permissions drwx-wx-wt. This means that all users can write to the directory, but only root can read. The result is that PHP can create session files, but cannot go back and read them later. This appears to be why your sessions are failing.

Fix the ownership and permissions so that www-data can both read and write (rwx). For instance:

chgrp www-data /var/lib/php5/session
chmod g+rwx /var/lib/php5/session

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.