Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Share Laravel's session and check authentication from external projects
<?php
/*
|--------------------------------------------------------------------------
| Sharing Laravel's session and checking authentication
|--------------------------------------------------------------------------
|
| Use the following code in any CMS (WordPress, Joomla, etc), filemanager (CKFinder,
| KCFinder, simogeos's Filemanager, etc), or any other non-Laravel project to boot into
| the Laravel framework, with session support, and check if the user is authenticated.
|
| The following code is tested with Laravel 4.2.11
| It may not work with Laravel 5
|
| Last update: 2015-01-09
|
*/
require '/path/to/laravel/bootstrap/autoload.php';
$app = require_once '/path/to/laravel/bootstrap/start.php';
$request = $app['request'];
$client = (new \Stack\Builder)
->push('Illuminate\Cookie\Guard', $app['encrypter'])
->push('Illuminate\Cookie\Queue', $app['cookie'])
->push('Illuminate\Session\Middleware', $app['session'], null);
$stack = $client->resolve($app);
$stack->handle($request);
$isAuthorized = Auth::check();
@frzsombor

This comment has been minimized.

Copy link
Owner Author

frzsombor commented Jan 9, 2015

All the time I tried integrating a filemanager (KCFinder, simogeo's Filemanager, etc), into a Laravel project, checking if the user is authenticated was always a problem. Reading a few Stackoverflow questions, and other forum/blog posts, it looks like from around 4.1.28, Application::boot() does not initialize sensitive session data anymore, so I had to create a solution to initialize the framework without actually calling Application::run().

Here are a few pages I've found about this issue:

stackoverflow.com: share session info with laravel and back
stackoverflow.com: How to integrate CKFinder with Laravel?
stackoverflow.com: Share Laravel authentication/session with PHP
laravel-tricks.com: Integrating Laravel >=4.1.28 with 3rd party libraries
jacopobeschi.com: Integrate Laravel And Session in external php application
laravel.io: Checking laravel auth in subdomain (wordpress)

I've linked this Gist to all of the above pages, so we can discuss if my
solution is better than the others, and if not, which is the best.
If we find a better solution, I will update this code.

Hope someone finds this useful!

@chilio

This comment has been minimized.

Copy link

chilio commented Feb 5, 2015

It is really useful and works good.
I believe there's one more important thing to notice.
If you are mixing native laravel routes with legacy app routes then Session:put() is not enough.
You also need to call Session::save() for the new variables to be persistent in Session (when invoked in legacy app route).
It would be greater if Session:put() would act same in both situations.

@djtechonline

This comment has been minimized.

Copy link

djtechonline commented Mar 18, 2015

Is it possible to do something like this with Laravel 5? I would like to integrate ResponsiveFilemanager (http://www.responsivefilemanager.com) to allow users to have their own home folders in a Laravel 5 project.

@jesseschutt

This comment has been minimized.

Copy link

jesseschutt commented Mar 22, 2015

I'd also like to know if this can work on Laravel 5. Thanks!

@menjaraz

This comment has been minimized.

Copy link

menjaraz commented May 18, 2015

For Laravel 5 try:

<?php

require '/path/to/laravel/bootstrap/autoload.php';
$app = require_once '/path/to/laravel/bootstrap/app.php';

$app->make('Illuminate\Contracts\Http\Kernel')
    ->handle(Illuminate\Http\Request::capture());

// An instance of the Laravel app should be now at your fingertip ;-)

...

$isAuthorized = Auth::check();
@calebfavor

This comment has been minimized.

Copy link

calebfavor commented Jul 2, 2015

This works great thanks!

@alex-petrea

This comment has been minimized.

Copy link

alex-petrea commented Jul 8, 2015

@menjaraz when trying the laravel 5 approach I get this "Cannot redeclare endsWith() (previously declared in .../vendor/hamcrest/hamcrest-php/hamcrest/Hamcrest.php:655)"

How can I avoid this?

@puntodamar

This comment has been minimized.

Copy link

puntodamar commented Aug 4, 2015

I'm sorry,
where do I put this code?

@amrigo

This comment has been minimized.

Copy link

amrigo commented Dec 7, 2015

How can i use this code to integrate Cakephp 2.5 and Laravel 5.1? so if the user has logged in into cakePHP the same login will be maintained into Laravel and vice-versa ?

@vk011

This comment has been minimized.

Copy link

vk011 commented Dec 19, 2015

This is great but how do I modify this code to be able to use Laravel's url() function as well?

@webafra

This comment has been minimized.

Copy link

webafra commented Dec 20, 2015

hello .

my Config.php file is :
require '../../bootstrap/autoload.php';
$app = require '../../bootstrap/start.php';

function CheckAuthentication()
{
return Auth::check();
}

but error in filemanager Page :
ErrorException (E_NOTICE)

Undefined variable: lang

laravel 4.2 .
please help me .

@szewang2805

This comment has been minimized.

Copy link

szewang2805 commented Feb 18, 2016

after some hour of study.
my solution is to use the default session variable available with ckfinder
$config['roleSessionVar'] = 'CKFinder_UserRole';

  1. in your controller or filter which determine user role, add this
    $_SESSION['CKFinder_UserRole'] = 'administrator';

and then in the config.php

$check = $_SESSION['CKFinder_UserRole'];

$config['authentication'] = function () use ($check){
   if ($check == 'administrator'){
    return true;
   }else{
    return false;
   }
};

now, only authorized user can access the ckfinder, but outsider are being blocked.

@farhantahir

This comment has been minimized.

Copy link

farhantahir commented Dec 22, 2016

Hi, I am using this way for getting csrf_token but problem is laravel boots up but the page gets break after booting laravel

my code is as follow:
$generate_csrf_token = function() use($csrf_token) {
require get_theme_root().'pathtolaravel/autoload.php';
$app = require get_theme_root().'pathtolaravel/start.php';
$request = $app['request'];
$client = (new \Stack\Builder)
->push('Illuminate\Cookie\Guard', $app['encrypter'])
->push('Illuminate\Cookie\Queue', $app['cookie'])
->push('Illuminate\Session\Middleware', $app['session'], null);
$stack = $client->resolve($app);
$stack->handle($request);
return csrf_token();
};

I have login page in wordpress and from that page I want to post on Laravel with csrf_token.
Any idea how can I get csrf token from laravel.

Edit: I am using laravel 4.2

@farhantahir

This comment has been minimized.

Copy link

farhantahir commented Dec 22, 2016

Edit: I thought I was using Laravel 4.2 but actually I am using Laravel 4.0.
In 4.0 there is method call in start.php as follow:

$app->redirectIfTrailingSlash();

It was causing the problem of stucking and breaking the page.

Solution: I created another start.php for wordpress called start_cms.php and commented the above method call in that.Now it works very well.

@octoxan

This comment has been minimized.

Copy link

octoxan commented Jan 23, 2017

Any ideas on how to get this working in Laravel 5.3?

So far I've gotten here...

require $_SERVER['DOCUMENT_ROOT'].'/../rbpoarentals/bootstrap/autoload.php';

$app = require $_SERVER['DOCUMENT_ROOT'].'/../laravel/bootstrap/app.php';

$kernel = $app->make('Illuminate\Contracts\Http\Kernel');
$response = $kernel->handle( $request = Illuminate\Http\Request::capture());

And it works on the Wordpress home page (example.com/) but no any subdirectories like example.com/page/.

I var_dump'd the $response and can see that the $response is the 404 page. So I could fix this by adding every single Wordpress url to my Laravels routes file... but that is messy. Any idea how I could have it start the Laravel app from the index no matter what Wordpress url I am at?

The 404 page on Laravel doesn't have access to the session.

@jcmosaiclearning

This comment has been minimized.

Copy link

jcmosaiclearning commented Dec 20, 2017

@octoxan I'm in the same boat. Curious if you ever solved the issue. The root path works fine, it's as though I need to allow the request to fall through all of laravel's routes and then be handled by wordpress. Along those lines I added the rollowing to the end of my web routes, which seems to be working(but I'm sure it has some sort of catch):

Route::get('{any?}', function ($any = null) {

});
@geraldarcega

This comment has been minimized.

Copy link

geraldarcega commented Jan 19, 2018

Hi! anyone manage to work this on 5.3 and up?

@tomsisk

This comment has been minimized.

Copy link

tomsisk commented Jul 9, 2018

The solution above for 5.2 should still work. In 5.5+ you just need to change bootstrap/autoload.php to vendor/autoload.php.

<?php

require '/path/to/laravel/vendor/autoload.php';
$app = require_once '/path/to/laravel/bootstrap/app.php';

$app->make('Illuminate\Contracts\Http\Kernel')
    ->handle(Illuminate\Http\Request::capture());

// An instance of the Laravel app should be now at your fingertip ;-)

...

$isAuthorized = Auth::check();
@dezashibi

This comment has been minimized.

Copy link

dezashibi commented Jul 10, 2018

Dear fellas

I tried to use the code for getting laravel auth check in an external php file but it always returns null
@tomsisk can you help me with it?
and would you please share the complete code for it

this is my code

`
require $path . '/vendor/autoload.php';

$app = require_once $path . '/bootstrap/app.php';

$app->make('Illuminate\Contracts\Http\Kernel')
    ->handle(Illuminate\Http\Request::capture());

return Auth::user();

`

it always returns null

@ghost

This comment has been minimized.

Copy link

ghost commented Jul 15, 2018

I managed to get mine to work properly in an external PHP file by manually starting the session before checking for auth data.
I am not certain if this has any side effects so use at your own risk.

Laravel 5.1

require '/path/to/bootstrap/autoload.php';
$app = require_once '/path/to/bootstrap/app.php';

$app->make('Illuminate\Contracts\Http\Kernel')->handle(\Illuminate\Http\Request::capture());
$id = $app['encrypter']->decrypt($_COOKIE[$app['config']['session']['cookie']]);

$session = $app['session']->driver();
$session->setId($id);
$session->start();

$isAuthenticated = $app['auth']->check();
@Oluwarufus

This comment has been minimized.

Copy link

Oluwarufus commented Aug 22, 2018

Tried this @ntanis in 5.5 but getting this error:

[2018-08-22 23:09:32] prod.ERROR: Undefined index: xxyyzz_session {"exception":"[object] (ErrorException(code: 0): Undefined index: xxyyzz_session at /home/...

Any known solution for 5.5?

@Developers-account

This comment has been minimized.

Copy link

Developers-account commented Jun 11, 2019

Laravel 5.4

require '/var/www/vhosts/xx.xxx.com/bootstrap/autoload.php';

$app = require_once '/var/www/vhosts/xxx.xxx.com/bootstrap/app.php';

$app->make('Illuminate\Contracts\Http\Kernel')->handle(Illuminate\Http\Request::capture());

$id = $app['encrypter']->decrypt($_COOKIE[$app['config']['session.cookie']]);

$session = $app['session']->driver();
$session->setId($id);
$session->start();

$isAuthenticated = $app['auth']->check();

if($isAuthenticated) {
echo 'logged in';
} else {
echo 'not';
}

I can get the laravel session data using above code to any PHP file.

@hongsolo9

This comment has been minimized.

Copy link

hongsolo9 commented Jul 9, 2019

Laravel 5.4

require '/var/www/vhosts/xx.xxx.com/bootstrap/autoload.php';

$app = require_once '/var/www/vhosts/xxx.xxx.com/bootstrap/app.php';

$app->make('Illuminate\Contracts\Http\Kernel')->handle(Illuminate\Http\Request::capture());

$id = $app['encrypter']->decrypt($_COOKIE[$app['config']['session.cookie']]);

$session = $app['session']->driver();
$session->setId($id);
$session->start();

$isAuthenticated = $app['auth']->check();

if($isAuthenticated) {
echo 'logged in';
} else {
echo 'not';
}

I can get the laravel session data using above code to any PHP file.

@Developers-account Don't work mate. $app->make('Illuminate\Contracts\Http\Kernel') is throwing a fit with the following error. "Call to a member function make() on boolean"

I need to understand Laravel indepth.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.