Session destroyed out of nowhere in PHP

9.8k views Asked by At

I am experiencing issue with a session being destroyed out of nowhere:

session_start(): Failed to decode session object. Session has been destroyed.

Kind of impossible to replicate the issue since I got this thrown in my server log.

Any ideas what could be the roots of that problem and/or where to start because I am getting that very rare (almost never).

4

There are 4 answers

0
Waqleh On

So I experienced this after migrating from Lighttpd webserver, PHP 5.6 to Nginx webserver, PHP 7.2, and at first it seamed so random, however, I was able to notice that this issue is user specific, where some of the users where able to login normally, but the server was not able to provide data from the session, so I checked read function in the custom session class and checked what data it was trying to serialize() and return, by using unset() I removed anything that I thought was not useful for the application to run before serialize() and return, and that seams to have solved the problem.

So the problem is either one or both:

  • too much data as @Luke Wenke suggested
  • data that cannot be handled as @Carl suggested

for more on the read function: https://www.php.net/manual/en/function.session-set-save-handler.php

0
Luke Wenke On

This happened to me when I was storing too much in $_SESSION where they were saved using serialize() in a table. Solution: don't store too much.

0
allthings dev On

Just in case the other answers didn't help you... This happened to me too recently, during development. In my environment, I was saving my sessions in a PostgreSQL DB using a sessions object. I used an object (a custom type) to set a session variable which caused the error. I was doing this

$username = new Name($httpRequest->username);
$_SESSION['username'] = $username;

Turned out it was because I was setting the session variable using a custom data type. I type-cast it to a primitive (string) by doing the following and the error went away.

$_SESSION['username'] = (string)$username;
2
Carl On

I had this problem as well and I discovered the problem was when someone posted an emoji. My current server set up couldn't handle these four bytes symbols, resulting "Failed to decode session object. Session has been destroyed".

What I did was to update to character set utf8mb4 with the collation utf8mb4_unicode_ci.

In order for this to work you need to make this change to your database, the database tables and the table columns. Also, in your application code, set the connection character set to utf8mb4.

This guide might help >