CKTIS / PHP
setcookie()
Queue a Set-Cookie response field before headers are sent.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
setcookie(string $name, string $value = "", array|int $expires_or_options = 0, string $path = "", string $domain = "", bool $secure = false, bool $httponly = false): boolQueue a Set-Cookie response field before headers are sent. Options include expires as a Unix timestamp, path, secure, httponly and samesite. Success indicates that PHP queued the cookie, not that a browser accepted it. The new value is available to PHP only on a later request that sends it. Since PHP 7.3 an options array can occupy the third positional argument. The parameter name is $expires_or_options; options: is unknown. An unknown option key raises ValueError since PHP 8.0.
Signature
setcookie(string $name, string $value = "", array|int $expires_or_options = 0, string $path = "", string $domain = "", bool $secure = false, bool $httponly = false): bool
Example output
true
[true,false,"ValueError","Error"]
Examples
<?php
if (PHP_SAPI==="cgi-fcgi") {
$ok=setcookie("theme","navy",["path"=>"/","httponly"=>true,"samesite"=>"Lax"]);
try {setcookie("theme","navy",["unknown"=>1]);} catch (ValueError $e) {$key=get_class($e);}
try {setcookie(name:"theme",value:"navy",options:[]);} catch (Error $e) {$named=get_class($e);}
echo json_encode([$ok,isset($_COOKIE["theme"]),$key,$named]);
exit;
}
$env=["REDIRECT_STATUS"=>"1","SCRIPT_FILENAME"=>__FILE__,"REQUEST_METHOD"=>"GET","QUERY_STRING"=>"qty=6"];
$proc=proc_open([PHP_BINDIR."/php-cgi"],[1=>["pipe","w"]],$pipes,null,$env);
$response=stream_get_contents($pipes[1]); fclose($pipes[1]); proc_close($proc);
[$headers,$body]=preg_split("/\\r?\\n\\r?\\n/",$response,2);
echo json_encode(str_contains($headers,"Set-Cookie: theme=navy")),"\n",$body;
Result
true [true,false,"ValueError","Error"]