PHP Tutorial > PHP Commands > Cookies
If you have a website, you may wish to set a cookie on the client computer so that your site will remember that user when she returns. PHP provides ways to create, retrieve, and delete cookies.
Cookies are set using the setcookie() function. The syntax is as follows:
Setcookie (name, value, expire, path, domain, secure)
name = name of the cookie.
value = value of the cookie.
expire = time when this cookie will expire. Unix time is used here.
path = the path on the server on which the cookie is available.
domain = the domain that the cookie is available.
secure = TRUE means the cookie should be trasmitted over a secure connection (https), FALSE otherwise. FALSE is the default.
All arguments except name are optional. Unix time is the number of seconds that have elapsed since January 1, 1970.
You must make sure that the setcookie() function is called before any HTML output is printed.
Let's take a look at a couple of examples:
This sets up a cookie with name = "cookie1" and value = "lisa". As expire time is not specified, this cookie will expire when the browser is closed.
This sets up a cookie with name = "cookie2" and value="electric1", and this cookies expires in 1 hour (3600 second).
Cookies can be retrieved via the $_COOKIE or the $_HTTP_COOKIE_VARS arrays. Assuming that the name of the cookie is "cookie1", the value of the cookie is retrieved by $_COOKIE['cookie1'].
To delete a cookie from a client computer, simply use the setcookie() function and set the expiration time as a time in the past. For example, the following code,
will get rid of the cookie with name = "cookie1" and value = "lisa".
Next: PHP Redirect