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

Exception or error:

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/


How to solve:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *