33

What is the artisan command for clearing all session data in Laravel, I'm looking for something like:

$ php artisan session:clear

But apparently it does not exist. How would I clear it from command line?

I tried using

$ php artisan tinker  
...
\Session::flush();

But it flushes session of only one user, I want to flush all sessions for all users. How can I do it?

I tried this:

artisan cache:clear

But it does not clear session, again.

Yevgeniy Afanasyev
  • 37,872
  • 26
  • 173
  • 191

10 Answers10

49

If you are using file based sessions, you can use the following linux command to clean the sessions folder out:

rm -f storage/framework/sessions/*
benjaminhull
  • 730
  • 6
  • 12
mitra razmara
  • 745
  • 6
  • 10
37

UPDATE: This question seems to be asked quite often and many people are still actively commenting on it.

In practice, it is a horrible idea to flush sessions using the

php artisan key:generate

It may wreak all kinds of havoc. The best way to do it is to clear whichever system you are using.


The Lazy Programmers guide to flushing all sessions:

php artisan key:generate

Will make all sessions invalid because a new application key is specified

The not so Lazy approach

php artisan make:command FlushSessions

and then insert

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use DB;

class flushSessions extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'session:flush';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Flush all user sessions';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        DB::table('sessions')->truncate();
    }
}

and then

php artisan session:flush
  • Oh, some one else approved it. Great. – Yevgeniy Afanasyev Jun 07 '18 at 04:03
  • 3
    Have fun logging your users out :D –  Jun 07 '18 at 04:04
  • 3
    Do note that generating a new app key will break any other data that you might have encrypted in Laravel. – Pablo Jun 07 '18 at 04:19
  • I wish I have a comprehensive list of this encrypted data, because [this](https://stackoverflow.com/questions/38980861/laravels-application-key-what-it-is-and-how-it-works#comment88473317_38980861) question is lacking a good answer. – Yevgeniy Afanasyev Jun 07 '18 at 23:04
  • 7
    Do NOT invalidate the apps key in a production app just because you want to get rid of sessions. It will also make all encrypted (not hashed) unreadable. Maybe your app doesn't store any encrypted data, but recommending it to strangers on StackOverflow doesn't seem to be a good idea. – miho Aug 26 '18 at 09:28
  • 15
    Also, the second part of the answer only works when you store your sessions to a database. Note that this might often not be the case (for ex. if you use the Redis session store or use the cookie session store). – miho Aug 26 '18 at 09:30
  • @miho Laravel's APP Key is only used to decrypt session cookies, therefore deleting them is a safe practice –  Sep 25 '18 at 02:57
  • 1
    @DevinGray Sadly, no. Check out the encryption documentation of Laravel, where it clearly says that the app key is used for all kind of encryptions: https://laravel.com/docs/5.7/encryption – miho Sep 25 '18 at 05:46
  • Significance of app key, https://stackoverflow.com/questions/49445420/what-is-the-significance-of-application-key-in-a-laravel-application – Shobi Nov 11 '18 at 20:48
  • It only works if your SESSION_DRIVER is database. It wouldn't work in all other cases: file, cookie, redis, etc. – sergei Nov 13 '18 at 10:31
  • I think it is not a good idea to regenerate the `APP_KEY` with `php artisan key:generate` because it will destroy all users passwords, isn't it? – algorhythm Dec 13 '18 at 13:25
  • 1
    What about the Redis driver. How access the session Redis connection ? – Boris D. Teoharov Jan 07 '19 at 12:55
  • @algorhythm - No it does not destroy user passwords, I tested and it didn't. But I think it should. – Yevgeniy Afanasyev Feb 20 '19 at 03:57
13

The problem is that PHP's SessionHandlerInterface does not force session drivers to provide any kind of destroyAll() method. Thus, it has to be implemented manually for each driver.

Taking ideas from different answers, I came up with this solution:

  1. Create command
php artisan make:command FlushSessions 
  1. Create class in app/Console/Commands/FlushSessions.php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class FlushSessions extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'session:flush';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Flush all user sessions';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $driver = config('session.driver');
        $method_name = 'clean' . ucfirst($driver);
        if ( method_exists($this, $method_name) ) {
            try {
                $this->$method_name();
                $this->info('Session data cleaned.');
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
        } else {
            $this->error("Sorry, I don't know how to clean the sessions of the driver '{$driver}'.");
        }
    }

    protected function cleanFile () {
        $directory = config('session.files');
        $ignoreFiles = ['.gitignore', '.', '..'];

        $files = scandir($directory);

        foreach ( $files as $file ) {
            if( !in_array($file,$ignoreFiles) ) {
                unlink($directory . '/' . $file);
            }
        }
    }

    protected function cleanDatabase () {
        $table = config('session.table');
        DB::table($table)->truncate();
    }
}
  1. Run command
php artisan session:flush

Implementations for other drivers are welcome!

jotaelesalinas
  • 1,387
  • 1
  • 11
  • 24
12

If you want completely remove session for any driver. Use this piece of code

\Session::getHandler()->gc(0); // Destroy all sessions which exist more than 0 minutes

Sometimes the most helpful answer is at the end

5

An easy way to get rid of all sessions is to change the name of the session cookie. This can be easily done by changing the 'cookie' => '...' line in config/session.php file.

This works independently of the session storage you use and also won't touch any other data except the session data (and thus seems preferable over the renewing the app key solution to me, where you would loose any encrypted data stored in the app).

miho
  • 11,765
  • 7
  • 42
  • 85
  • 1
    Nice solution, thx. And you are right. The `APP_KEY` is also a salt for hashes created with `Hash::make()`. So users password and any other hashed data will be invalid after changing it. – algorhythm Dec 13 '18 at 20:59
  • Why is it better than changing `domain` in the same file? – Yevgeniy Afanasyev Feb 20 '19 at 03:53
  • 1
    @algorhythm bcrypt passwords will keep working. Unsure about other password hashing algorythms. You are correct about manually hashed database columns though that use the Laravel encryption functionality (because those need to be decrypted, unlike passwords). – Flame Jan 18 '20 at 02:31
1

This thread is quite much old. But I would like to share my implementation of removing all sesssions for file based driver.

        $directory = 'storage/framework/sessions';
        $ignoreFiles = ['.gitignore', '.', '..'];
        $files = scandir($directory);

        foreach ($files as $file) {
            if(!in_array($file,$ignoreFiles)) unlink($directory . '/' . $file);
        }

Why I have not used linux command 'rm'?

Because PHP is one of the prerequisites for Laravel and Linux is not. Using this Linux command will make our project implementable on Linux environment only. That's why it is good to use PHP in Laravel.

Hamees A. Khan
  • 136
  • 1
  • 10
1

My solution Laravel

// SESSION_DRIVER=file


$files = File::allFiles(storage_path('framework/sessions/'));
foreach($files as $file){
  File::delete(storage_path('framework/sessions/'.$file->getFilename()));
}
//OR

//SESSION_DRIVER=redis

Artisan::call('cache:clear'); // == php artisan cache:clear 
1

I know this is an old thread, but what worked for me is just remove the cookies.

In Chrome, go to your develop console, go to the tab "Application". Find "Cookies" in the sidebar and click on the little arrow in front of it. Go to your domainname and click on the icon next to the filter field to clear the cookies for your domain. Refresh page, and all session data is new and the old ones are removed.

Refilon
  • 3,334
  • 1
  • 27
  • 51
0

If you use database session , just delete all data on that table. In my case it is 'sessions' table.

Nur Uddin
  • 1,798
  • 1
  • 28
  • 38
0

If you are using the database for session driver, then empty the sessions table. Regenerating the key will cause a lot of problems if you are using single login on many subdomains. Emptying the session table helps reduce the useless data in the session table. You can delete cookies on everyone's browswer.

Etta
  • 339
  • 4
  • 10