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 typically small text files embedded by the server into the user's computer. Whenever a computer requests a page through a 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, this 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 for the cookie. |
domain | Optional. Specifies the domain of the cookie. |
secure | Optional. Specifies whether the cookie is transmitted over a secure HTTPS connection. |
Tips and Comments
Note:You can access the value of a cookie named "user" through $HTTP_COOKIE_VARS["user"] or $_COOKIE["user"].
Note:When sending cookies, the cookie values are automatically URL-encoded. They are URL-decoded upon reception. If you do not need this, you can use setrawcookie(); Instead.
Instance
Example 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> ... ...
Example 2
Different methods to retrieve cookie values:
<html> <body> <?php // Output an individual cookie echo $_COOKIE["TestCookie"]; echo "<br />"; echo $HTTP_COOKIE_VARS["TestCookie"]; echo "<br />"; // Output all cookies print_r($_COOKIE); ?> </body> </html>
Output:
my cookie value my cookie value Array ([TestCookie] => my cookie value)
Example 3
// Delete a cookie by setting the expiration date to a past date/time
<?php // Set expiration date to one hour ago setcookie ("TestCookie", "", time() - 3600); ?> <html> <body> ... ...
Example 4
Create an array cookie:
<?php setcookie("cookie[three]","cookiethree"); setcookie("cookie[two]","cookietwo"); setcookie("cookie[one]","cookieone"); // Output cookie (after page reload) if (isset($_COOKIE["cookie"])) { foreach ($_COOKIE["cookie"] as $name => $value) { echo "$name : $value <br />"; } } ?> <html> <body> ... ...
Output:
three : cookiethree two : cookietwo one : cookieone