Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / PHP

setcookie()

Prepara un campo Set-Cookie prima dell’invio delle intestazioni.

Versione: PHP 8.4; repository runtime, production runtime not attested

Sintassi

setcookie(string $name, string $value = "", array|int $expires_or_options = 0, string $path = "", string $domain = "", bool $secure = false, bool $httponly = false): bool

Prepara un campo Set-Cookie prima dell’invio delle intestazioni. Le opzioni includono expires come timestamp Unix, path, secure, httponly e samesite. true indica che PHP ha accettato il cookie per l’invio. Il valore arriva a PHP in una successiva richiesta che lo rimanda. Da PHP 7.3 un array di opzioni può occupare la terza posizione. Il parametro è $expires_or_options e options: non esiste. Da PHP 8.0 una chiave di opzione ignota causa ValueError.

Firma

setcookie(string $name, string $value = "", array|int $expires_or_options = 0, string $path = "", string $domain = "", bool $secure = false, bool $httponly = false): bool

Output dell’esempio

true
[true,false,"ValueError","Error"]

Esempi

<?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;

Risultato

true
[true,false,"ValueError","Error"]

Fonti