Setting a Cookie
To set a cookie in PHP is a simple matter. As long as no HTML has yet been transferred, you can call the setcookie function, which has the following syntax (see following Table):
setcookie(name, value, expire, path, domain, secure, httponly);
Parameter |
Description |
Example |
---|---|---|
name | The name of the cookie. This is the name that your server will use to access the cookie on subsequent browser requests. | username |
value | The value of the cookie, or the cookie’s contents. This can contain up to 4 KB of alphanumeric text. | Hannah |
expire | (optional) Unix timestamp of the expiration date. Generally, you will probably use time() plus a number of seconds. If not set, the cookie expires when the browser closes. |
time() + 2592000 |
path | (optional) The path of the cookie on the server. If this is a / (forward slash), the cookie is available over the entire domain, such as www.webserver. com. If it is a subdirectory, the cookie is available only within that subdirectory. The default is the current directory that the cookie is being set in and this is the setting you will normally use. |
/ |
domain | (optional) The Internet domain of the cookie. If this is webserver.com, the cookie is available to all of ebserver.com and its subdomains, such as www.webserver.com and images.webserver.com. If it is images.webserver. com, the cookie is available only to images.webserver.com and its subdomains such as sub.images.webserver.com, but not, say, to www.webserver.com. |
.webserver.com |
secure | (optional) Whether the cookie must use a secure connection (https://). If this value is TRUE, the cookie can be transferred only across a secure connection. The default is FALSE. |
FALSE |
httponly | (optional; implemented since PHP version 5.2.0) Whether the cookie must use the HTTP protocol. If this value is TRUE, scripting languages such as JavaScript cannot access the cookie. (Not supported in all browsers). The default is FALSE. |
FALSE |
So, to create a cookie with the name username and the value “Hannah” that is accessible across the entire web server on the current domain, and removed from the browser’s cache in seven days, use the following:
setcookie('username', 'Hannah', time() + 60 * 60 * 24 * 7, '/');