PHP setcookie()
Function
Definition and Usage
The setcookie()
function sends an HTTP cookie to the client.
A cookie is a variable sent by the server to the browser. Cookies are typically small text files embedded by the server into the user's computer. Whenever the same computer requests a page through a browser, this cookie is also sent.
The name of the cookie is automatically assigned to a variable of the same name. For example, if a cookie named "user" is sent, a variable named $user is automatically created, containing the value of the cookie.
The cookie must be assigned a value before any other output is sent to the client.
The function returns TRUE on success and FALSE on failure.
Syntax
Parameter | 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. time()+3600*24*30 will set the cookie to expire in 30 days. If this parameter is not set, the cookie will automatically expire when the session ends (i.e., when the browser is closed). |
path | Optional. Specifies the server path of the cookie. If the path is set to "/", the cookie will be valid within the entire domain. If the path is set to "/test/", the cookie will be valid in the test directory and all its subdirectories. The default path value is the current directory where the cookie is located. |
domain | Optional. Specifies the domain of the cookie. To make the cookie valid for all subdomains of example.com, you need to set the cookie's domain to ".example.com". When you set the cookie's domain to www.example.com, the cookie is only valid in the www subdomain. |
secure | Optional. Specifies whether the cookie should be transmitted over a secure HTTPS connection. Set to TRUE if the cookie needs to be transmitted over a secure HTTPS connection. The default is FALSE. |
Tips and Notes
Tip: You can access the value of a cookie named "user" through $HTTP_COOKIE_VARS["user"]
or $_COOKIE["user"]
.
Note: When sending a cookie, the cookie's value is automatically URL-encoded. Upon receiving, it is automatically URL-decoded. If you do not need this, you can use setrawcookie()
instead.
Example 1
Setting and sending a cookie:
Example 2
Different methods to retrieve the cookie value (after the cookie is set):
The above code will output:
Example 3
Deleting a cookie by setting the expiration date to a past date/time:
Example 4
Creating an array cookie:
The above code will output: