PHP setcookie() function

Definition and usage

The setcookie() function sends an HTTP cookie to the client.

Cookies are variables sent from the server to the browser. Cookies are usually small text files embedded by the server into the user's computer. Whenever a computer requests a page through the browser, this cookie is sent.

The name of the cookie is specified as the same-named variable. For example, if the sent cookie is named "name", a variable named $user will be automatically created, containing the value of the cookie.

Cookies must be assigned before any other output is sent.

If successful, the function returns true, otherwise it returns false.

Syntax

setcookie(name,value,expire,path,domain,secure)
Parameters Description
name Required. Specifies the name of the cookie.
value Required. Specifies the value of the cookie.
expire Optional. Specifies the expiration time of the cookie.
path Optional. Specifies the server path of the cookie.
domain Optional. Specifies the domain of the cookie.
secure Optional. Specifies whether cookies are transmitted through a secure HTTPS connection.

Tips and comments

Note:You can access the value of the cookie named "user" through $HTTP_COOKIE_VARS["user"] or $_COOKIE["user"].

Note:During the sending of cookies, the value of the cookie is automatically URL-encoded. During reception, it is URL-decoded. If you do not need this, you can use setrawcookie() Rimpiazza.

Esempio

Esempio 1

Set and send cookie:

<?php
$value = "my cookie value";
// Send a simple cookie
setcookie("TestCookie",$value);
?>
<html>
<body>
...
...
<?php
$value = "my cookie value";
// Send a cookie that expires in 24 hours
setcookie("TestCookie",$value, time()+3600*24);
?>
<html>
<body>
...
...

Esempio 2

Ricerca di vari metodi per il valore del cookie:

<html>
<body>
<?php
// Output an individual cookie
echo $_COOKIE["TestCookie"];
echo "<br />";
echo $HTTP_COOKIE_VARS["TestCookie"];
echo "<br />";
// Output tutti i cookie
print_r($_COOKIE);
?>
</body>
</html>

Output:

my cookie value
my cookie value
Array ([TestCookie] => my cookie value)

Esempio 3

// Eliminare un cookie impostando la data di scadenza a una data/ora passata

<?php
// Impostare la data di scadenza a un'ora fa
setcookie ("TestCookie", "", time() - 3600);
?>
<html>
<body>
...
...

Esempio 4

Creare un array cookie:

<?php
setcookie("cookie[three]","cookiethree");
setcookie("cookie[two]","cookietwo");
setcookie("cookie[one]","cookieone");
// Output cookie (dopo il ricarico della pagina)
if (isset($_COOKIE["cookie"]))
  {
  foreach ($_COOKIE["cookie"] as $name => $value)
    {
    echo "$name : $value <br />";
    }
  }
?>
<html>
<body>
...
...

Output:

three : cookiethree
two : cookietwo
one : cookieone