PHP cookie | How to set, get and delete cookies in PHP

Introduction to cookies in PHP

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

These days many sites are using cookies as the way to store user’s information. However visitor has option to disable or enable cookies at their browsers. This is why important information should not be stored at user’s computers that affect functionality of web application.

The difference between cookies and session is cookies store information at client side (visitors computer) whereas session stores information at 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 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 says “save id/pass for 7 days” and so on.

Example of setting cookies

We will set two cookies in 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 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 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 name only however it might not work always. So better is to use past date argument as well.