Cookies are small files that are created by the browser and stored on the client's computer. Cookies are useful for tailoring a website to a particular user. It is a way for the web page to remember a user and some information about him or her.
For example, you could use cookies to remember a user's username for them, so they don't have to type it in everytime they visit the login page.
Have a look at the PHP cookies tutorial below to help get you started.
You must call the setcookie function before your script starts to output any data. That is, before any print or echo statements.
setcookie(name, value, expire, path, domain);
For most of the time, you won't need to specify the last 2 parameters in the function.
Let us set a cookie and dive right into some serious PHP programming:
<?php $expire = time()+ 60; // current time plus 60 seconds setcookie("name", "John Doe", $expire); if (isset($_COOKIE["name"])) { echo "I remember you " . $_COOKIE["name"] . "!<br />"; } else { echo "You're new around here"; } ?>
The first time you visit the page (or every minute after that when the cookie expires) you will see:
If you view the page again within a minute of seeing the first message you will see:
That's all there is to setting cookies in PHP.
Suppose you set a cookie with a much longer life and you want to delete it. All you do is set the same cookie again, but this time with a expiry date that is in the past.
<?php // set the expiration date to one minute ago setcookie("name", "", time()- 60); ?>
Run that code and the cookie is lost and forgotten.
Be careful when coding websites that rely heavily on cookies. Not all browsers support cookies (although most modern ones do) and not all users have cookies turned on in their browsers. You don't want to have a situation where your site does not work at all for a user simply because they do not have cookies turned on.
Try to write your code so that cookies add extra functionality and that no cookies will give regular functionality.