Failed to read session data on PHP7.1

xtempore picture xtempore · Jan 9, 2017 · Viewed 32.6k times · Source

Sharing a problem that I had (and now solved).

On my development machine, I run IIS with PHP. I upgraded to PHP7 and suddenly my code no longer worked, returning this error...

session_start(): Failed to read session data: user (path: C:\WINDOWS\temp)

It looks like a permissions issue, right? So, I spent a long time tweaking php.ini settings and trying to change folder permissions - with no success.

Then I realised something. See my answer below.

Answer

xtempore picture xtempore · Jan 9, 2017

I finally realised the message was meaningless - the application implements its own session handler using the database. In the read method, I get the session data as a string from the database.

class Sess implements SessionHandlerInterface
...
    public function read($key)
    {
        $qKey = U_Data::quote($key);
        $dt = U_Data::datetime();
        $sql = <<<EOT
SELECT `sess_data` FROM `sess`
WHERE `sess_key` = $qKey 
AND `sess_exp_ts` > $dt
ORDER BY `sess_exp_ts` DESC
LIMIT 1
EOT;
        return U_Data::getOneVal($sql);
    }

The U_Data::getOneVal method has a second parameter to return if there is no matching data. The default is null and that worked fine in PHP5, but in PHP7.1 it causes the error. A simple change to have it return an empty string instead solved the problem.

        return U_Data::getOneVal($sql, '');

So there it is. If you are getting a warning about session_start not working AND you are implementing your own session handler, try checking your code in the read method to make sure it always returns a string.

(Note: U_Data is just my own data utility class)

I hope this saves someone else the hours I spent racking my brain!