Creating cookies via PHP couldn’t be simpler: anywhere in the document (normally before anything else is written to the page), you can create a cookie with the
<?php setCookie("name","value"); ?>
The name of the cookie can be anything that follows web conventions, and the value can be a string, Boolean value, or number.
Once it is set, you read a cookie from any page as a variable (keeping in mind that you cannot set a cookie and read it in the same session). So creating a cookie with:
<?php setCookie("cookietest", "test"); ?>
Could be displayed at a later point with:
<?php echo $_COOKIE['cookietest']; ?>
This cookie will last as long as the browser remains running: you can close the window or tab that contains your web page and re-open it, and the cookie will still be there. However, the moment you quit the browser, the cookie will be discarded. To make the cookie permanent, you need to give it an expiry date.
time() is a fascinating function. The easiest way to understand it is to simply echo it on a PHP page:
<?php echo time(); ?>
time() is a constant record of the number of seconds that have passed since midnight of January 1, 1970, Greenwich Mean Time, aka the “Unix Epoch”. Most Unix-based operating and file systems (i.e. the majority of the Internet) do not think of time in terms of BC or AD, but as the number of seconds that have elapsed from this point.
The current moment always represented by
time(). 30 seconds into the past would be
time() – 30; one minute into the future would be
time() + 60, and one hour would be
time() + (60 × 60) (sixty seconds multiplied by sixty minutes = the number of seconds in an hour). To give our cookie an expiry date 30 days from now, we would create it with:
<?php setCookie("cookietest", "test", time() + (60*60*24*30)); ?>
Now the cookie will last even if the browser or computer is shut down, until 30 days have elapsed since the cookie was set.
Note that this does not guarantee that the cookie will be present the next time the user returns: the cookie could be wiped or blocked, the hard drive reformatted, etc. You can see, and manipulate, the cookies set inside your browser: in Firefox, you will find this under Firefox / Preferences / Privacy / Remove Individual Cookies