The setcookie() function is the heart and soul of cookies in PHP. It can be used to both set and unset cookies. It's syntax is as follows:
setcookie(string name [, string value [, int expire [, string path [, string domain [, int secure]]]]])
- name - The name of the cookie, by which it is accessed.
- value - The value that the cookie holds. Must be accessed via the name. If left blank, the cookie will expire when the browser is closed.
- expire - The time when the cookie expires, as a UNIX timestamp.
- path - The path by which the cookie may be accessed on the server. '/' allows it to be accessed through the whole domain. If the path is set to '/folder', the cookie will be available in '/folder' and all of its sub folders.
- domain - The domain that the cookie is available on.
- secure - Whether or not the cookie should be transmitted over a secure HTTPS connection.
All of these parameters, except for name, are optional. To skip them, just use "" in their place for strings, and 0 for integers.
In this example, the cookie 'user_name' will be set with the value of 'kristopher'. Since expire is not given, the cookie will expire when the browser window is closed.
Important: The setcookie() function MUST be set before any output whatsoever is sent to the browser. No echo statements, HTML, or blank spaces can come before setcookie() is called.
To access the value of cookies, you use the superglobal $_COOKIE. To retrieve our user_name, we would do the following:
This cookie is the same as above, however it will not expire for 30 days (unless updated by the script or deleted by the user). We set the path equal to '/', so that any folder on the domain may access the cookie.
setcookie('user_name', 'kristopher', time()+60*60*24*30, '/');
To delete or unset a cookie, simply set its expiration date to a negative (or past) value. Such as:
This would set the cookie to expire an hour ago, thus deleting the cookie.
setcookie('user_name', 'kristopher', time() - 3600, '/');