Access Laravel Session Outside Laravel
I had a scenario that I wanted access an active Laravel session OUTSIDE Laravel.
Given that the native.php is in the same server as the laravel project.
Let native be in:
c:\xampp\htdocs\sandbox\native.php
Let laravel project be in:
c:\projects\laravel\
Native is served via XAMPP
http://localhost/sandbox/native.php
Laravel is served on port 8000
php artisan serve
And this is what I came up with:
https://gist.github.com/jcbagtas/0e981885e72e383e0f0d582db14de8af
Explanation:
function getLaravelUser()
{
//Initialize Laravel's App Container
require 'c:\projects\laravel\bootstrap\autoload.php';
require 'c:\projects\laravel\native\bootstrap\app.php';
//Resolve the given type from the container.
$app->make('Illuminate\Contracts\Http\Kernel')->handle(Illuminate\Http\Request::capture());
//Fetches the native $_COOKIE variable generated by the Laravel's instance for the Client's machine.
//The Container will call the encrypter class to decrypt the cookie and get it's ID.
//Session driver will be called along with the info from the Auth::user();
$id = $app['encrypter']->decrypt($_COOKIE[$app['config']['session.cookie']]);
$app['session']->driver()->setId($id);
$app['session']->driver()->start();
return $app['auth']->user();
}
If you try and print out $id, you will see that the name of the cookie will be shown.
You can verify that cookie in your browser's Option/Settings.
Comments