Cookies are stored in text files that sit on the client machine. Web pages with the right permissions can read from and write to cookies. They 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, set the expiration date to sometime in the past, like this.
setcookie('flavor','chocolate chip', time()-10000);
Cookies are set in the HTTP header, so they must be set before any HTML code is passed back to the browser.