In This Tutorial:
These days many sites are using cookies as the way to store user’s information. However, a visitor has the option to disable or enable cookies at their browsers. This is why the important information should not be stored at user’s computers that affect the functionality of web application.
The difference between cookies and session is cookies store information at the client side (visitors computer) whereas session stores information at the server side.
Creating or setting cookies is an easy task. See the syntax below
setcookie(name, value, expiration)
setcookie has three parameters
- name – Sets the name of cookie at user’s computer. You must remember the name of the cookie in order to retrieve in future. E.g. UserID
- value – The value to be saved. E.g. 1234
- expiration – duration after which cookie will be expired/destroyed. For example, some email interfaces say “save id/pass for 7 days” and so on.
Example of setting cookies
We will set two cookies in the visitor’s computer as follows
$cookie_expire = time()+10800;
setcookie("Visitorname", "Mike", $cookie_expire);
setcookie("Visitorage", "20", $cookie_expire);
That’s it. The above code will set two cookies Visitorname and Visitorage and will expire in three hours.
Depending on your browser, chrome, firefox, IE or other you can see yourself after executing the above code. See the image below how cookie looks like in Chrome.
$_COOKIE[‘cookie_name’] is used to access cookies in PHP. This is how we can access cookies in PHP for the above created cookie.
Example of accessing cookie
$name = $_COOKIE['Visitorname'];
echo "stale cookies!";
echo "Name stored in cookie is - ". $name;
Name stored in cookie is – Mike
The above example uses to access created cookie [visitorname] which value was set to “Mike”. In the previous example.
You have to use setcookie() again in order to delete a cookie. For that, you should specify name argument and use a past date.
setcookie( "Visitorname", "", time()- 60);
setcookie( "Visitorage", "", time()- 60);
- You need to set cookies at header i.e. even before using any HTML or other codes.
- You can remove a cookie by using the name only, however, it might not work always. So better is to use past date argument as well.