Cookies in PHP
PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() function. Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser. You can use the output buffering functions to delay the script output until you have decided whether or not to set any cookies.
Any cookies sent to you from the client will automatically be turned into a PHP variable just like GET and POST method data, depending on the register_globals and variables_order configuration variables. If you wish to assign multiple values to a single cookie, just add [ ] to the cookie name.
setcookie()
int setcookie ( string name [, string value [, int expire [, string path [, string domain [, int secure]]]]])
setcookie() defines a cookie to be sent along with the rest of the header information. Cookies must be sent before any other headers are sent (this is a restriction of cookies, not PHP). This requires you to place calls to this function before any or
tags.All the arguments except the name argument are optional. If only the name argument is present, the cookie by that name will be deleted from the remote client. You may also replace any argument with an empty string ("") in order to skip that argument. The expire and secure arguments are integers and cannot be skipped with an empty string. Use a zero (0) instead. The expire argument is a regular Unix time integer as returned by the time() or mktime() functions. The secure indicates that the cookie should only be transmitted over a secure HTTPS connection.
Once the cookies have been set they can be accessed on the next page load with the $_COOKIE array (which used to be called $HTTP_COOKIE_VARS in PHP versions prior to 4.1.0).
- Cookies will not become visible until the next loading of a page that the cookie should be visible for.
- Cookies must be deleted with the same parameters as they were set with.
Examples:
setcookie ("TestCookie", $value); setcookie ("TestCookie", $value,time()+3600); /* expire in 1 hour */ setcookie ("TestCookie", $value,time()+3600, "/~rasmus/", ".utoronto.ca", 1);Examples (delete):
// set the expiration date to one hour ago setcookie ("TestCookie", "", time() - 3600); setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", ".utoronto.ca", 1);