When a user leaves your website and then returns at a later time or date, you may want to remember them from their previous visit. This is done using cookies.
Cookies are stored by the browser on the client machine. Web pages with the right permissions can set, read, and delete cookies. Cookies are generally used to track user information between visits.
In PHP, cookies are set with the
setcookie() function, which can take several parameters including:
- The cookie's name (required).
- The cookie's value.
- The cookie's expiration date (if this isn't set, the cookie will expire when the browser window is closed).
- The directory path on the server that can read the cookie.
- The domain name that can read the cookie.
- A flag indicating whether the cookie should only be read over HTTPS.
The following code will set a cookie that expires in one week.
setcookie('flavor','chocolate chip', time()+60*60*24*7);
There is no
deletecookie() function. To delete a cookie on the client, set the value to an empty string and set the expiration date to sometime in the past, like this (0 is the epoch):
Note that setting the cookie's expiration date to a date in the past only deletes the cookie on the client. It will not delete it on the server.
Cookies are set in the HTTP header, so they must be set before any HTML code is passed back to the browser.
Together, the files below illustrate how cookies work:
To delete the cookie on both the client and the server, navigate to http://localhost:8888/Webucator/php/Authentication/Demos/delete-cookie-fully.php: