setcookie()
function is used to define cookies sent with the remaining HTTP headers.
Cookies are often used to identify users. A cookie is a small file that the server embeds on the user's computer. Every time the same computer requests a page through the browser, it sends the cookie. Using PHP, you can create and retrieve cookie values.
The name of the cookie is automatically assigned to a variable with the same name. For example, if a cookie named "user"
is sent, a variable named $user
is automatically created, which contains the value of the cookie.
Note: setcookie()
function must appear before the <html>
tag.
Note: When sending a cookie, the value of the cookie will be automatically URL-encoded; when receiving, it will be automatically decoded (to prevent URL encoding, please use setrawcookie()
instead).
setcookie ( name , value , expire , path , domain , secure , httponly ) ;
parameter | describe |
---|---|
name | Required. Specify the name of the cookie. |
value | Optional. Specifies the value of the cookie. |
Expire |
Optional. Specifies the expiration time of the cookie. The value time()+86400*30 will cause the cookie to expire after 30 days. If this parameter is omitted or set to 0, the cookie will expire at the end of the session (i.e. when the browser is closed). The default is 0. |
path |
Optional. Specifies the server path of the cookie. If set to "/", the cookies are available for the entire domain. If set to "/php/", cookies are only available for the php directory and all its subdirectories. The default value is the current directory where the cookie is set. |
domain |
Optional. Specify the domain name of the cookie. To make cookies available in all subdomains of example.com, set domain to "example.com". Setting it to www.example.com will make cookies available only in the www subdomain. |
Secure |
Optional. Specifies whether to transmit cookies only over a secure HTTPS connection. TRUE means that cookies are set only if a secure connection exists. The default is FALSE. |
httponly |
Optional. If set to TRUE, cookies can only be accessed via the HTTP protocol (cookies cannot be accessed through the scripting language). This setting helps reduce identity theft through XSS attacks. The default is FALSE. |