Introduction to cookies in PHP

Cookies are the way to save information at client/visitor side. The information is usually related to the visitor like login id, passwords, selected shopping cart items. Many big websites use cookies usually those who allow saving passwords/ids e.g. Gmail, Facebook etc.

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.

How to Set cookies in PHP

Creating or setting cookies is an easy task. See the syntax below

Syntax:

setcookie(name, value, expiration)

setcookie has three parameters

  1. 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
  2. value – The value to be saved. E.g. 1234
  3. 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

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.

Get cookie in PHP

$_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

Output

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.

Delete cookie in PHP

You have to use setcookie() again in order to delete a cookie. For that, you should specify name argument and use a past date.

Example

Tips regarding cookies

  • 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.