Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper syntax for setcookie() in php 7.3?

Tags:

php

setcookie

What is the proper syntax for setcookie() in PHP 7.3? I usually use setcookie() like this:

setcookie("genone", "genoneinfo", "$cookie_expiration_time","/","",1,1);

That works, but how do I add the samesite option? I have tried like this, but it fails with php errors:

setcookie("genone", "genoneinfo", "$cookie_expiration_time","/","",1,1,['samesite'=>'Lax']);

errors: PHP Warning: setcookie() expects at most 7 parameters, 8 given zzz.com/index.php on line 73, referer: https://zzz.com/

Thanks, Todd

like image 782
nrsbus Avatar asked Mar 02 '23 16:03

nrsbus


1 Answers

PHP 7.3 introduced an alternative syntax for setcookie():

An alternative signature supporting an options array has been added. This signature supports also setting of the SameSite cookie attribute.

That means you only supply the first two arguments as you would in the old version and place the remaining ones in an array of options:

setcookie('genone', 'genoneinfo', [
    'expires' => $cookie_expiration_time,
    'path' => '/',
    'domain' => '',
    'secure' => true,
    'httponly' => true,
    'samesite' =>'Lax',
]);

Here parameter names from the old version become array keys, as per their description in the docs:

An associative array which may have any of the keys expires, path, domain, secure, httponly and samesite. The values have the same meaning as described for the parameters with the same name.

like image 58
El_Vanja Avatar answered Mar 05 '23 15:03

El_Vanja