CKTIS / PHP
setcookie()
Prépare un champ Set-Cookie avant l’envoi des en-têtes.
Version : PHP 8.4; repository runtime, production runtime not attested
Syntaxe
setcookie(string $name, string $value = "", array|int $expires_or_options = 0, string $path = "", string $domain = "", bool $secure = false, bool $httponly = false): boolPrépare un champ Set-Cookie avant l’envoi des en-têtes. Parmi les options figurent expires en temps Unix, path, secure, httponly et samesite. true indique la prise en charge par PHP. La valeur n’arrive à PHP que dans une requête ultérieure renvoyant le cookie. Depuis PHP 7.3 un tableau d’options peut occuper la troisième position. Le paramètre est $expires_or_options et options: est inconnu. Depuis PHP 8.0 une clé d’option inconnue déclenche ValueError.
Signature
setcookie(string $name, string $value = "", array|int $expires_or_options = 0, string $path = "", string $domain = "", bool $secure = false, bool $httponly = false): bool
Sortie de l’exemple
true
[true,false,"ValueError","Error"]
Exemples
<?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;
Résultat
true [true,false,"ValueError","Error"]