简体   繁体   English

Laravel 5.4 Cookie值

[英]Laravel 5.4 Cookie Value

I am trying to get the value of a cookie. 我正在尝试获取Cookie的价值。

1 When I use Laravel's request cookie helper: 1当我使用Laravel的请求cookie助手时:

$request->cookie('CookieName');

Laravel returns the cookie's name instead of its value. Laravel返回cookie的名称而不是其值。

2 When I dd() the the cookie() function: 2当我dd()cookie()函数时:

dd(cookie('CookieName'));

I get: 我得到:

#name: "CookieName"
#value: null
#domain: null
#expire: 0
#path: "/"
#secure: false
#httpOnly: true
-raw: false
-sameSite: null

3 When I use PHP's build in $_COOKIE function: 3当我在$ _COOKIE函数中使用PHP的构建时:

$_COOKIE['CookieName'];

I actually get the cookie's value. 我实际上得到了cookie的价值。


Is there a way I can get Lavavel to return the cookie's value? 有没有办法让Lavavel返回cookie的值?

The correct way to fetch the cookie value is as you've used 获取Cookie值的正确方法是您使用过的方法

$request->cookie('name');

But the cookie helper method makes a new cookie, not fetches the value. 但是cookie帮助程序方法会创建一个新的cookie,而不是获取值。 So when you do dd(cookie('CookieName')); 所以当你做dd(cookie('CookieName')); , its creating a cookie with that name and no value and returning it. ,它会创建一个具有该名称且没有值的cookie并将其返回。

Laravel encrypts and decrypts the cookie value on the fly without any user intervention. Laravel无需用户干预即可即时加密和解密cookie值。 Check how you're setting the cooking again and also make sure you've set the APP_KEY which will be used for the encryption. 检查您如何再次设置烹饪方式,并确保已设置将用于加密的APP_KEY Changing this key would invalidate all the older cookies. 更改此密钥将使所有较早的cookie失效。

Actually 其实

$value = $request->cookie('name');

should give a value as you can read in doc . 应该给出一个值,您可以在doc中阅读。

I suspect that your cookie is set from some external code (not laravel code) for example it is created by jQuery plugin or something. 我怀疑您的Cookie是由某些外部代码(而非laravel代码)设置的,例如它是由jQuery插件或其他工具创建的。 In that situation you must add your cookie to EncryptCookies middleware $except table. 在这种情况下,您必须将cookie添加到EncryptCookies中间件$ except表中。 Because all cookies created by the Laravel framework are encrypted and signed with an authentication code. 因为Laravel框架创建的所有cookie均已加密并使用身份验证代码签名。 All other cookies for example from jQuery plugin are not encrypted and signed by Laravel thus $request->cookie('name') can't see them or their value. 例如,来自jQuery插件的所有其他cookie均未经过Laravel加密和签名,因此$ request-> cookie('name')无法看到它们或它们的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM