Cookies work by storing data on the user’s machine when they visit a page. That is the data is stored on the user’s own PC, the web server writes data to the PC via the browser. As this is done by the browser the user can change their browser settings to block cookies and stop a web server writing data to it. Cookies will only therefore work on browsers that have cookies enabled. Most web users work with cookies ‘on’ but be aware they can and are switched off by some users. As such when using cookies the first thing to do is to test for their presence.
To define a cookie use setcookie(). You must ensure that this function is before any output from a script as cookies are set via the HTTP headers of a HTML document. Any output here includes whitespacing. If setcookie() appears after any output then an error will occur.
setcookie(string CookieName, string CookieValue, int CookieExpireTime, path, domain, int secure);
Warning: If you place setcookie() after any outputs from echo or print it will fail.. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction).
To call the cookie use $_COOKIE['mycookie']
This page has a cookie set to act as a page counter. At the start of this document is the following code:
This must appear before any HTML or indeed any whitespacing.
Then the following code outputs the counter.
As previously mentioned cookies will be deleted when the browser is shut (the session ends) if no expiry date is set. Alternatively they will expire based on the expiry date set. To remove cookies when the browser window is open reset the cookie with a negative expiry date.
The page linked to below has the following code in:
The setcookie() has function has a negative expiry time so the 'count' cookie is removed. The 'header' function redirects the user back to this page.
Therefore the following code should output a value of 0.