How to access the globals $_SESSION and $_COOKIE f

2019-01-27 20:28发布

I am working on a laravel project that needs to work besides a custom php project, because that I need to get access to the pure php globals $_SESSION and $_COOKIE in the laravel app.

Until now I'm geting just null or empty. Somebody know how to do that?

5条回答
Rolldiameter
2楼-- · 2019-01-27 20:50

I had a similar issue with CakePHP a couple of months ago. Basically, the session variables in the Cake application were completely independent of the session variables in the bespoke application that we had. The issue was that Cake uses a different session identifier than PHPSESSID. In the end, I was forced to bridge the gap by forcing Cake to use PHPSESSID. I'm not too familiar with Laravel, but from what I can see (on their main site), they seem to be using "laravel_session" instead of PHPSESSID. This is most likely your issue and there seems to be a topic about this on the offical Laravel forums.

查看更多
闹够了就滚
3楼-- · 2019-01-27 20:50

The answer for sessions is so simple that I don't believe at the begining that it will actually work.

I was thinking that Laravel somehow override the default behavior of the normal PHP Sessions. Maybe declaring a custom session_handler or some other magic behind the scenes.

Thanks for all the answers I got here, I discover that Laravel doesn't actually use the $_SESSION at all, it implements a completely different driver.

So, to have acesses to the external session, I just use the native session_start() and session_name() in pure PHP and now I have acess to all data save in the global $_SESSION on the same namespace used in the side project.

For cookies, I can't figure out yet how to do it, from the Laravel app :/. But just with sessions I can go ahead and merge the apps.

查看更多
疯言疯语
4楼-- · 2019-01-27 20:59

Laravel has its own implementations of $_SESSION and $_COOKIE, so I'm afraid you cannot access them via those superglobals.

To try to overcome that, what you can do, in your Laravel app, is to transfer data from one to the other by doing something like:

foreach(Session::all() $key => $value)
{
    $_SESSION[$key] = $value;
}
查看更多
做个烂人
5楼-- · 2019-01-27 21:04

Laravel has its own implementation of those globals, but you can access them over Symfony request class - which is parent of Laravel request. Symfony is working directly with globals.

Session:

Request::getSession();

Cookie:

$cookie = new ParameterBag($cookie_name);
查看更多
放荡不羁爱自由
6楼-- · 2019-01-27 21:13

I had similar problem with cookies, which weren't being set by laravel and Cookie::get() returned null. It's because laravel encrypts their cookies. You can just not include EncryptCookies middleware to avoid this problem. Remove \App\Http\Middleware\EncryptCookies::class from $middlewareGroups in app\Http\Kernel.php

查看更多
登录 后发表回答