Setting cookies in Laravel Octane / Swoole

620 Views Asked by At

I'm attempting to set cookies on Laravel Octane, however the cookies appear to be not defined on the given index.

setcookie(self::JWT_TOKEN_COOKIE, $token_details['access_token'], [
         'httponly' => true,
         'expires' => time() + $token_details['expires_in'],
         'path' => '/'
]);

die($_COOKIE[self::JWT_TOKEN_COOKIE]);

When attempting to print the Cookie, I get an error telling me it hasnt been set.

Undefined array key "JWT_TOKEN"

Is there something wrong in the way I'm setting cookies in Laravel Octane? Is there a new class I should be using to use these as the application is now fully held in RAM/loaded once?

1

There are 1 best solutions below

0
On BEST ANSWER

The setcookie function add the Set-Cookie header

Superglobal array $_COOKIE reads from the Cookie header

Remove the die function and reload the page, cookie will appear

Example

<?php

setcookie('a', 'b', ['httponly' => true, 'expires' => time() + 30, 'path' => '/']);

print_r($_COOKIE);

Request to the script with saving cookies to tmp file

curl http://localhost:8000/ -c /tmp/cookies.txt --verbose
> GET / HTTP/1.1
> Host: localhost:8000
> User-Agent: curl/7.68.0
> Accept: */*
> 
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
<---------- setcookie ---------->
< Set-Cookie: a=b; expires=Sun, 27-Mar-2022 23:50:36 GMT; Max-Age=30; path=/; HttpOnly
< 
<---------- print_r ---------->
Array 
(
)
* Closing connection 0

Request to the script with saved cookies

curl http://localhost:8000/ -b /tmp/cookies.txt --verbose
> GET / HTTP/1.1
> Host: localhost:8000
> User-Agent: curl/7.68.0
> Accept: */*
<---------- readed from /tmp/cookies.txt ---------->
> Cookie: a=b
> 
<---------- setcookie ---------->
* Replaced cookie a="b" for domain localhost, path /, expire 1648425170
< Set-Cookie: a=b; expires=Sun, 27-Mar-2022 23:52:51 GMT; Max-Age=30; path=/; HttpOnly
< 
<---------- print_r ---------->
Array
(
    [a] => b
)
* Closing connection 0

Use laravel response object to send the cookie

https://laravel.com/docs/9.x/responses#attaching-cookies-to-responses