无法在 laravel 中设置 cookie

Can't set cookie in laravel

我正在使用 Laravel 4 来开发我的应用程序。但是我在设置 cookie 时遇到了一些问题。这是 app/routes.php 中的一些代码:

Route::get('/', function(){
    // Set a cookie before a response has been created ??
    Cookie::queue('test0', '123', 10);

    $app = App::getFacadeApplication();
    $version = $app::VERSION;

    //Creating Custom Responses
    $response = Response::make("<html><body>
        Version: $version <br/>
        <script type=\"text/javascript\">
            document.write(document.cookie);
        </script>
        </body></html>", 200);

    $response->withCookie(Cookie::make('test1', '0123', 10));

    //Queue after response created
    Cookie::queue('test2', '123', 10);
    Cookie::queue('test3', '123', 10);
    setcookie('test4', '123', time() + 60*10);

    return $response->withCookie(Cookie::make('test5', '0123', 10));
});

但是当我 运行 这段代码时,它并没有设置所有值。这是我的结果:

只有 php 内置函数有效, Cookie::queuewithCookie 等任何其他功能对我不起作用,但在上图的 Cookies set by this page 弹出窗口中,它仍然具有所有 cookie 值
那么,这里的问题是什么?
为什么 test2 的值不是 '123' ???

这是因为您设置的cookie是HttpOnly cookie

HttpOnly cookies can only be used when transmitted via HTTP (or HTTPS). They are not accessible through non-HTTP APIs such as JavaScript. This restriction mitigates, but does not eliminate, the threat of session cookie theft via cross-site scripting (XSS). HttpOnly cookies are supported by most modern browsers.

Cookie::make() 方法有七个参数。您可以在 laravel 中将 httpOnly(默认为 true)设置为 false。

Cookie::make($name, $value, $minutes, $path, $domain, $secure, $httpOnly);

编辑

在 laravel 中,出于安全原因,cookie 值使用在 app/config/app.php 中设置的密钥自动加密。要得到你想做的事,你需要遵循这两种方式:

只需在php中使用传统的setCookie方法即可。

setcookie($name, $value, $expire, $path, $host, $secure, $httpOnly);

否则,你可以使用这种取巧的方法。 Accessing unencrypted cookies

希望对你有用。