62

I Want to run my application in localhost with php artisan serve but I get this Error unserialize(): Error at offset 0 of 40 bytes where is my problem?

Hanie Asemi
  • 1,318
  • 2
  • 9
  • 23
  • 1
    Do you use it out of the box? Or in which code part does the error appear? It's a bit difficult to help you without some code or more informations. – René Höhle Aug 13 '18 at 08:16
  • how I can explain my problem?I just get this Error in all page of application @Stony – Hanie Asemi Aug 13 '18 at 08:19
  • try `php artisan serve -vvv`. Afair this should display a more verbose output for your error and you can probably find the cause. – Tschitsch Aug 13 '18 at 08:19
  • @Tschitsch I test it but get just this Error – Hanie Asemi Aug 13 '18 at 08:21
  • Then you probably should dig into some advanced debugging techniques for php, otherwise its really hard to help you, sorry. Try to introduce a custom error_handler in order to get some detailed output first. I assume that your application relies on some serialized representation of something, but we cannot know. – Tschitsch Aug 13 '18 at 08:26
  • 1
    What version of Laravel are you using? There are some changes after 5.6.30 that may cause this. Check the upgrade guide for more info https://laravel.com/docs/5.6/upgrade#upgrade-5.6.30 – Adrian Hernandez-Lopez Aug 13 '18 at 08:51
  • @AdrianHernandez-Lopez version of my laravel is 5.6,this work before but Now I get this Error – Hanie Asemi Aug 13 '18 at 11:27
  • @AdrianHernandez-Lopez your answer help me I Created new laravel and copy this .env file to this project,I'm deleting .env file and use old version file – Hanie Asemi Aug 13 '18 at 11:40

14 Answers14

92

You have to set a news Key Generate because

php artisan key:generate

After that test again to run the Laravel Application

php artisan serve
Yann Assoumou
  • 921
  • 5
  • 4
82

I got the same error, when I upgrade a Laravel 5.5 app to 5.6. The error comes form the EncryptCookies-Middleware.

Delete the cookies in your browser and/or clear your session-files in your Laravel app.

stefanzweifel
  • 1,434
  • 14
  • 9
27

I've faced same problem. I frequently faced this problem in Homestead-vagrant environment. To solve this issue in Laravel 5.4,5.5,5.6 or more -

php artisan config:clear

php artisan view:clear

php artisan key:generate

Asad Zaman
  • 475
  • 5
  • 10
  • 1
    php artisan config:clear may or may not be needed depending on your set up. I didn't need that one, but I did need the next 2. – Jay Dec 05 '19 at 23:51
7

I got the same error a couple of days ago when I pushed a production update to my Laravel project from Envoyer.

Immediate fix: I tried to rollback to the previous commit but the issue persisted which means the issue was originating from the client side, cookies probably. I tried removing cookies and the issue was gone.

Later, I spent a lot of time looking for this issue but got nothing until I faced this issue again today with another deployment and i found this article on Laravel news about the security fix 5.6.30 update. I was able to identify that this issue occurs if i try to deploy previous (< 5.6.30) version of the laravel v5.6.26 for a project which was already using > v5.6.30 and cookies were already created ( not serliazed) which when <5.6.30 version of the framework tries to unserlize results in error because they're not properly serealized.

  • Installing laravel/framework (v5.6.26) Loading from cache

From the upgrade guide:

Configuring Cookie Serialization Since this vulnerability is not able to be exploited without access to your application's encryption key, we have chosen to provide a way to re-enable encrypted cookie serialization while you make your application compatible with these changes. To enable / disable cookie serialization, you may change the static serialize property of the App\Http\Middleware\EncryptCookies middleware:

I was able to fix this issue permanently by clearing cache of composer so forcing it to load latest version of the framework instead of falling back to cache.

Hope this helps.

Bests,

qadeerkhan
  • 85
  • 11
  • _I was able to fix this issue permanently by clearing cache of composer_ what was the command you used to do that? `composer dump-autoload`? – abbood Aug 27 '19 at 03:41
5

Just Inspect the element in Browser, and go to application tab and select cookie and delete that all cookie. That's It.

enter image description here

Bedram Tamang
  • 3,748
  • 31
  • 27
3

In App\Exceptions\Handler under render function use this snippet, it will reset browser cookie.

if (str_contains($exception->getMessage(), 'unserialize')) {
    $cookie1 = \Cookie::forget('laravel_session');
    $cookie2 = \Cookie::forget('XSRF-TOKEN');

    return redirect()->to('/')
                 ->withCookie($cookie1)
                 ->withCookie($cookie2);
}
3

In my case I did removed my composer.lock and did a composer install and voila...

$ cd project_root
$ rm composer.lock
$ composer install
Shobi
  • 10,374
  • 6
  • 46
  • 82
  • 1
    Work for me in Laravel 5.5 – Sundbox Oct 22 '18 at 08:04
  • it's never a good idea to just delete composer.lock. This may work when u're working with a hello world app on your desktop, but not on a production app. See more details here: https://stackoverflow.com/a/49593368/766570 – abbood Aug 20 '19 at 12:02
  • I do that all the time. If you have pinned the versions correctly in composer.json it shouldn't be a problem at all. at least from my experience. – Shobi Aug 20 '19 at 12:21
  • Normally in composer.json you don't specify exact versions of dependencies but rather a min version and above. Without composer.lock, running composer install will install the latest stable version of a particular dependency which might no longer work with your app. – pkid169 Aug 21 '19 at 05:13
  • I know and I agree. And normally I won't log in to production and delete `composer.lock` or any file and do composer install. – Shobi Aug 21 '19 at 09:04
3

In my case, I was trying to decrypt a hash with an wrong function.

I was creating encrypt using encryptString()

$hash = Crypt::encryptString('secret');

but I tried to decrypt using decrypt()

$value = Crypt::decrypt($hash);

the correct way is

$value = Crypt::decryptString($hash);

So when you encrypt using Crypt::encrypt() you must decrypt it using Crypt::decrypt(), and for Crypt::encryptString() use Crypt::decryptString()

Roy Ryando
  • 1,058
  • 12
  • 30
2

I also encountered this issue when I happened to update my composer. If you put

protected static $serialize = true;

inside App\Http\Middleware\EncryptCookies, the old cookie will break your system. So to prevent this, either you have to clear the cookie, or just don't unserialize the decrypted cookie.

I made a workaround for this: Inside vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php Above this line of decrypt() function:

return $unserialize ? unserialize($decrypted) : $decrypted;

add:

try {
            return $unserialize ? unserialize($decrypted) : $decrypted;
        } catch (\Exception $e){
            return $decrypted;
        }

This might be ugly, but you can temporarily put it there until you think the old cookies has gone.

Nghia Le
  • 343
  • 3
  • 10
  • Interesting. But why not just remove the old cookie in the browser? – molerat Mar 04 '19 at 09:14
  • @molerat sure you can just clear your cookies but if your site has been public to many users then probably you don't want to interrupt their experience. – Nghia Le Mar 05 '19 at 11:39
  • Good point. Wasn’t thinking about that because my environment is still all local and private at this point. – molerat Mar 05 '19 at 12:13
  • your fix won't work when you update your laravel, since the update will wipe our your changes (inside the vendor directory). This answer works for localhost hello world apps, but production apps – abbood Aug 20 '19 at 12:04
  • @abbood yes, that's why i said it's a temporarily fix until the old cookies from your users gone. Or else you can override this method to make this a permanent fix. – Nghia Le Aug 21 '19 at 23:23
2

The first thing you should do is clear the configuration cache file

php artisan config:clear

Then create a new key for the application

php artisan key:generate

Finally, restart the server.. I hope it will fix your problem.

Nehad Awad
  • 39
  • 3
1

In my case happened during local development. The steps that caused the problem was:

  1. I upgraded the laravel up to 5.8 on a seperate branch.
  2. I switched into an another branch having laravel 5.2 (in my case I had to review a PR)

I also was logged in in my app and hence there was a session cookie as well. In that case I just cleared the browser's cookies and got fresh ones.

In firefox can be done via visiting then select about:preferences#privacy and select the appropriate option. as the following images show (in Greek)

Privacy setting and an indication where the user to click Setting to clean its cookies as well

An anothwer aproach to diagnose the issue it to open a private firefox window or use chrome's cognito mode.

Dimitrios Desyllas
  • 9,082
  • 15
  • 74
  • 164
0

In my case, it was related to route cache

php artisan route:clear
-2

yeah, for localhost you can just delete cookies, but for production put this in your error handler so users would not see whoops :

if (strpos($exception->getMessage(), 'unserialize(): Error at offset 0 of 40 bytes') === 0) {
    unset($_COOKIE['laravel_session']);
    unset($_COOKIE['XSRF-TOKEN']);

    setcookie('laravel_session', null, -1, '/');
    setcookie('XSRF-TOKEN', null, -1, '/');

    abort(200, '', ['Location' => route('frontend.home')]);
}

PS. tested for laravel 5.6.

fico7489
  • 7,931
  • 7
  • 55
  • 89
-5

you will just run in terminal

composer global update
Tohid Da
  • 1
  • 6