PHP creating cookies setting and deletingCookies are used by web sites to store information about the visitor at the hard disk of the user computer through the browser. The difference between session and cookies is the cookies are stored at client computer and the sessions are stored at server side. The user have full control over the cookies it want to store or not and for what level it wants to store. The browser setting for the cookies can be managed by going to
Unlike sessions cookies are managed by users through its web browser so we have to carefully select which data to be used through cookies.
Sending cookies by setcookie
The above line will set the cookie with the variable value set to a string. This will expire after one hour as the time of expire is set to one huour ( +3600 seconds ) than the present time. We have used Unix time stamp to get the present time value and then added the expire time of the cookies in seconds.
Two things we have to know here.
1. Cookie set by the page now will be available at next page.
2. Before sending any header to the browser ( before sending any html code ) the cookie has to be set. Otherwise error message we will get.
Reading cookiesTo read the cookie we can check the value as a variable or by using the code below.
In PHP 5 and above it is
Delete CookiesSame way to delete the cookies we will set the same cookie again with expire time one hour before by using time()-3600 . That will delete the cookie from the computer.
This will delete the cookie. Here is the demo of this script.
Download the ZIP file here cookies.zip