Reputation: 2350
I'm using Laravel 4 to develop my application. But I have some problem about setting cookie. Here is some code in 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));
});
But when I run this code, it doesn't set all value. Here is my result:
Only the php build-in function work,
any other function like Cookie::queue
, withCookie
didn't work for me, but in the Cookies set by this page
popup like the image above, it still have all cookie value
So, what is the problem here?
And why the value of test2
is not '123'
???
Upvotes: 0
Views: 7045
Reputation: 3584
This is because the cookie you set is 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()
method takes seven parameters. You can set httpOnly
(default is true) to false in laravel.
Cookie::make($name, $value, $minutes, $path, $domain, $secure, $httpOnly);
Edit
In laravel, cookie value is automatically encrypted with key which is set in app/config/app.php
for security reason. To get what you want to do, you need to follow this two ways :
Just use traditional setCookie method in php.
setcookie($name, $value, $expire, $path, $host, $secure, $httpOnly);
Otherwise, you can use this tricky way. Accessing unencrypted cookies
Hope it will be useful for you.
Upvotes: 4