Funzione PHP setcookie()
Esempio
L'esempio seguente crea un cookie denominato "user" con il valore "John Doe". Il cookie scadrà dopo 30 giorni (86400 * 30). La "/" significa che il cookie è disponibile in tutto il sito (in caso contrario, seleziona la directory che preferisci).
Recuperiamo quindi il valore del cookie "utente" (usando la variabile globale $_COOKIE). Utilizziamo anche la funzione isset() per scoprire se il cookie è impostato:
<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Definizione e utilizzo
La funzione setcookie() definisce un cookie da inviare insieme al resto delle intestazioni HTTP.
Un cookie viene spesso utilizzato per identificare un utente. Un cookie è un piccolo file che il server incorpora nel computer dell'utente. Ogni volta che lo stesso computer richiede una pagina con un browser, invierà anche il cookie. Con PHP, puoi creare e recuperare i valori dei cookie.
Il nome del cookie viene automaticamente assegnato ad una variabile con lo stesso nome. Ad esempio, se è stato inviato un cookie con il nome "utente", viene automaticamente creata una variabile denominata $utente, contenente il valore del cookie.
Nota: la funzione setcookie() deve apparire PRIMA del tag <html>.
Nota: il valore del cookie viene automaticamente codificato nell'URL all'invio del cookie e decodificato automaticamente alla ricezione (per impedire la codifica dell'URL, utilizzare invece setrawcookie() ).
Sintassi
setcookie(name, value, expire, path, domain, secure, httponly);
Valori dei parametri
Parameter | Description |
---|---|
name | Required. Specifies the name of the cookie |
value | Optional. Specifies the value of the cookie |
expire | Optional. Specifies when the cookie expires. The value: time()+86400*30, will set the cookie to expire in 30 days. If this parameter is omitted or set to 0, the cookie will expire at the end of the session (when the browser closes). Default is 0 |
path | Optional. Specifies the server path of the cookie. If set to "/", the cookie will be available within the entire domain. If set to "/php/", the cookie will only be available within the php directory and all sub-directories of php. The default value is the current directory that the cookie is being set in |
domain | Optional. Specifies the domain name of the cookie. To make the cookie available on all subdomains of example.com, set domain to "example.com". Setting it to www.example.com will make the cookie only available in the www subdomain |
secure | Optional. Specifies whether or not the cookie should only be transmitted over a secure HTTPS connection. TRUE indicates that the cookie will only be set if a secure connection exists. Default is FALSE |
httponly | Optional. If set to TRUE the cookie will be accessible only through the HTTP protocol (the cookie will not be accessible by scripting languages). This setting can help to reduce identity theft through XSS attacks. Default is FALSE |
Dettagli tecnici
Valore di ritorno: | VERO sul successo. FALSO in caso di fallimento |
---|---|
Versione PHP: | 4+ |
Registro delle modifiche PHP: | PHP 5.5 - Un attributo Max-Age è stato incluso nell'intestazione Set-Cookie inviata al client PHP 5.2 - È stato aggiunto il parametro httponly |
Altri esempi
Esempio
Diverse date di scadenza per i cookie:
<?php
$value = "Hello world!";
// cookie will expire when the browser close
setcookie("myCookie", $value);
// cookie will expire in 1 hour
setcookie("myCookie", $value, time() + 3600);
// cookie will expire in 1 hour, and will only be available
// within the php directory + all sub-directories of php
setcookie("myCookie", $value, time() + 3600, "/php/");
?>
<html>
<body>
...some code...
</body>
</html>
Esempio
Per modificare un cookie è sufficiente impostare (di nuovo) il cookie utilizzando la funzione setcookie():
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Esempio
Per eliminare un cookie, utilizzare la funzione setcookie() con una data di scadenza nel passato:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Esempio
Crea un piccolo script che controlla se i cookie sono abilitati. Per prima cosa, prova a creare un cookie di prova con la funzione setcookie(), quindi conta la variabile array $_COOKIE:
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
❮ Riferimento alla rete PHP