Cookies allow you to store bits of information on users' computers. This information can be used for many purposes, including remembering settings from a previous visit, login details, and much more.
PHP makes it very easy to use cookies. To set a cookie using PHP we need to use the setcookie function, documented here: setcookie(). Use of this function must be before any other output to the page, including HTML tags, whitespace, etc. If you call the function after there has been other output to the page, PHP will give you a nice warning message and the cookie will not be set.
The setcookie function consists of six parameters. I will explain the first four of these parameters in this tutorial. If you would like information on the last two, visit the documentation link above.
setcookie(name, value, expire, path, domain, secure);
|
|
Here is an example code for setting a cookie, try it yourself:
<?php
|
|
Accessing Your Cookies
To access cookies once they've been set, simply use the superglobal array $_COOKIE. Try this example code after you've set a cookie using the code above:
<?php
|
|
This should print "My name is Ron." to the page.
Cookie ExpirationTo have the cookie expire at a certain time we use the third parameter of the setcookie function. The default expiration of a cookie (if you don't set a value for the third parameter) is when the user closes his or her browser window.
The expire parameter expects an integer value, in most cases you would use the time() function and add the number of seconds you want the cookie to expire from the time it is set. The time() function is used to generate the current Unix timestamp. For more information on timestamps visit http://php.net/time.
Here is an example:
<?php
|
|
Now our cookie will automatically be removed from the user's computer one day from the time it is set.
Cookie PathIf you want your cookie to only be available within a certain path of your website use the fourth parameter. The default path of the cookie is the current directory from which the cookie is being set.
For example, if you want your cookie to be available to the "guestbook" directory of your site then set the path parameter to "/guestbook/". If you want your cookie to be available within the entire domain, set the path parameter to "/".
Here is some sample code:
<?php
|
|
That's the basics of setting and accessing cookies. Try setting some of your own cookies with different expirations and paths and further experiment with the setcookie function. Good Luck!
| Discuss Tutorial: Cookies via PHP | 14 Comments |





