Esercitazione PHP

PHP HOME Introduzione a PHP Installazione PHP Sintassi PHP Commenti PHP Variabili PHP PHP Eco/Stampa Tipi di dati PHP Stringhe PHP Numeri PHP PHP matematica Costanti PHP Operatori PHP PHP Se...Altro...Altro Passaggio PHP Ciclo PHP Funzioni PHP Array PHP Superglobali PHP RegEx PHP

Moduli PHP

Gestione dei moduli PHP Convalida del modulo PHP Modulo PHP richiesto URL/e-mail del modulo PHP Modulo PHP completo

PHP avanzato

Data e ora PHP PHP Include Gestione dei file PHP Apri/Leggi file PHP Creazione/scrittura di file PHP Caricamento file PHP Cookie PHP Sessioni PHP Filtri PHP Filtri PHP avanzati Funzioni di callback PHP PHP JSON Eccezioni PHP

PHP OOP

PHP Che cos'è OOP Classi/Oggetti PHP Costruttore PHP PHP distruttore Modificatori di accesso PHP Ereditarietà PHP Costanti PHP Classi astratte PHP Interfacce PHP Tratti PHP Metodi statici PHP Proprietà statiche PHP Spazi dei nomi PHP Iterabili PHP

Database MySQL

Database MySQL MySQL Connect MySQL Crea DB MySQL Crea tabella Dati di inserimento MySQL MySQL Ottieni l'ultimo ID MySQL inserisce più MySQL preparato MySQL Seleziona dati MySQL dove MySQL Ordina per MySQL Elimina dati Dati di aggiornamento MySQL Dati limite MySQL

PHP XML

Parser XML PHP Analizzatore PHP SimpleXML PHP SimpleXML - Ottieni PHP XML espatriato PHP XML DOM

PHP - AJAX

Introduzione all'Ajax AJAX PHP Database AJAX XML AJAX Ricerca in tempo reale AJAX Sondaggio AJAX

Esempi PHP

Esempi PHP compilatore PHP Quiz PHP Esercizi PHP Certificato PHP

Riferimento PHP

Panoramica di PHP matrice PHP Calendario PHP Data PHP Directory PHP Errore PHP Eccezione PHP File system PHP Filtro PHP PHP FTP PHP JSON Parole chiave PHP PHP Libxml Posta PHP PHP matematica PHP Varie PHP MySQLi Rete PHP Controllo dell'output PHP RegEx PHP PHP SimpleXML Flusso PHP Stringa PHP Gestione delle variabili PHP Analizzatore XML PHP Zip PHP Fuso orario PHP

Funzione PHP setcookie()

❮ Riferimento alla rete PHP

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