Nick John Bueno
Nick John Bueno

Reputation: 111

How to fix unserialize() error

I was working in a project using Laravel 4.2 and suddenly an accidentally blackout occurred and when I oppened my project again, I encountered this error:

unserialize(): Error at offset 0 of 319 bytes

This happens in any page of the project. How can I fix this?

enter image description here

Upvotes: 1

Views: 2992

Answers (2)

Keitel Jovin
Keitel Jovin

Reputation: 41

I don't know if it's too late to give an answer here. I'm using Laravel 4.2 for a project an I encountered this problem 4 times from now. It seems that it happens when PC freezes or compelled to shutdown while Laravel is writing on session file.

Solutions:

1- Not encourage in production. You have to delete all session files in app/storage/session.

Laravel session for a user (or a PC) is linked to a Client side Cookie, and Laravel will create a session file for each of the Browser that requests info on your server. You dont know what file is for each user when looking at the files. So deleting all session files is will destroy all users sessions. I found a work around which is programatically deleting the single session for that single User (or Browser) and the User will only have to retry, and it will work.

2- Only if you are force to handle an urgency on Production. This will be a 4 lines codes in 2 files. In your picture, a method readFromHandler is called in Store class in Illuminate\Session\Store.php, Add a global variable to catch the SessionId (that is the real file name of the session file):

protected function readFromHandler()
{
    $data = $this->handler->read($this->getId());

    $GLOBALS['sess_id'] = $this->getId();

    return $data ? unserialize($data) : array();
}

And there is a file that handle all Errors in Laravel before even getting the App ready: \Illuminate\Exception Handler.php . Change method handleEror to this:

public function handleError($level, $message, $file = '', $line = 0, $context = array())
{
    //Ensure the error is about unserialize() and is coming from Store.php
    if(strpos ($message, 'unserialize(): Error at offset') !== false && 
        strpos ($file, 'Store.php') !== false)
        unlink('../app/storage/sessions/'.$GLOBALS['sess_id']);

    if (error_reporting() & $level)
    {
        throw new ErrorException($message, 0, $level, $file, $line);
    }
}

I know you shouldn't change Laravel Core, but I hope this will help you and other people to understand it and to come up with a better and 100% acceptable solution.

Upvotes: 3

jde
jde

Reputation: 198

Sometimes, char encoding can mess up your serialized objects / variables.

Try to use base64 to be safe in all cases : Encode :

$var = "somestuff"; 
$ouput = serialize(base64encode($var)); 

Decode :

$var = base64decode(unserialize($ouput);)

Upvotes: 1

Related Questions