PHP Cookies


Today we will learn a new concept called cookies in this PHP Cookies tutorial.

  • HTTP is a stateless protocol. It don’t have the ability to remember the things such as which pages a client visited in a website, which options did he select etc.
  • To remember these things cookies are used.
  • Cookies are also called as HTTP Cookies, web cookies or browser cookies.
  • Cookies are nothing but simple text files that contain some information generated by server.
  • We can say when a client connects to a server first time; the server gives an identification number to that client, stores it in a text file and sends this text file known as cookie along with the response to the client.
  • When after some period of time, if the client again happens to visit the same server, the cookie file stored at clients PC is sent to that server along with the request. The server then uses this cookie information to identify the client.
  • The cookies are mainly used to remember the stateful information in a website such as products added to a cart while purchasing items online, remembering the pages visited in a website, to store the username and password to login to a website so that the user doesn’t have to put username and password everytime to login, to remember the user’s username, etc.
  • Cookies can be sometimes harmful because they can bring in viruses with them. Cookies can remain stored in user’s PC or they can vanish when the browser is closed.
  • A cookie can only be accessed by the browser that set it, i.e. the cookie set by Firefox cannot be accessed by IE and vice-a-versa.
  • So let us learn the mechanism to create, update, delete and use cookies in this tutorial further.

Creating a cookie:

  • A cookie is mainly a key value pair. Creating or setting a cookie requires a name, value, expiry time, a domain where it will be accessed, etc.
  • The expiry time is the period given in which the client browser will store the cookie. Once this time expires, the browser will forget the cookie.
  • The cookie can be set or created using a setcookie() function.
  • Syntax of setcookie() function:
  • It consists of 6 parameters as explained below:
    • Name: this parameter sets the name of the cookie.
    • Value: This is the value of the cookie and is the actual content that you want to store.
    • Expiry: This is the time given in seconds after which the cookie will become inaccessible. This parameter is not mandatory. If the expiry of the cookie is not set it will expire automatically when the browser is closed.
    • Path: It provides the directories for which the cookie is valid. A single forward slash character makes the cookie to be available for all directories.
    • Domain: This can be used to specify the domain in which they are valid. All cookies are only valid for the host and the domain in which they were created.
    • Security: it specifies how the cookie should be transmitted. If this parameter is set to 1 i.e. true, the cookie will be transmitted through secure connection using HTTPS. But if this parameter is set to 0 i.e. false, the cookie will be transmitted through unsecure connection using regular HTTP.
  • Cookies are usually set in an HTTP header. Hence the function setcookie() should appear before the html tags, so that a cookie is sent before the HTML is set to the page. Otherwise it will not work.
  • Let us demonstrate the creation of cookies using an example.
  • To demonstrate it, create a new folder named cookies in the htdocs folder in xampp folder located in C drive. Open a new notepad++ document and save it as index.php in this newly created cookies folder.
  • Write the code in index.php as given below:
  • Run the code in index.php page by opening the browser and writing the address localhost/cookies in the address bar.
  • The above code is used to set cookies with names “username” and “pwd”.
  • We can set number of cookies we want. But we have to use the function setcookie() for every cookie to be set.
  • We have used the setcookie() function to set the cookies “username” and “pwd” in the above code as shown below:
  • Here the setcookie() function to set the cookie username contains cookie name as username, value of the cookie as pranita, expiry time of 1 hour, path accessible to all directories using a forward slash (“/“) and security as 1 i.e. to allow cookie transmission through secure connection like HTTPS.
  • The expiry time of 1 hour for the cookie username is obtained by adding 3600 sec to the value of time() function, because (1hr=60min and 60min=60*60 sec).
  • The function time() returns the current date and time.
  • Next a cookie named pwd is set with name as pwd and value as pranita@123.
  • This pwd cookie will expire as soon as the browser accessing it is closed. i.e. it will not be stored for a long time, since no expiration time was given.
  • In the above code when these cookies are set, the echo statement is executed giving the information that the cookies are set.
  • The output is shown below:

  • fig 1

  • Value of the cookie is automatically URL encoded when sending the cookie and it is automatically URL decoded when received.
  • If we want to send the cookie without URL encoding the cookie value, we can use function setrawcookie() instead of setcookie() to set the cookie.
  • The function setrawcookie() has same parameters as passed in setcookie() function.

Retrieving a cookie value:

  • A very simple way exists to access the cookie values in PHP.
  • We use the super global array variable $_COOKIE which is has global scope.
  • This $_COOKIE array variable stores the key-value pair of cookie(s) in it.
  • Once the cookies are set, they can be accessed on next page load.
  • Let us access the cookies username and pwd set in the above example.
  • First write the following statement in index.php page:
  • This statement redirects the user to access_cookie.php page where we want to display the cookies values.
  • Now open a new notepad++ document and save it as access_cookie.php in the folder cookies where index.php page is saved and write the following code there:
  • In the above code, we have retrieved the values from cookies username and pwd.
  • Before retrieving the value it is checked, whether the cookie is set to any value or not using isset() function.
  • If the cookie is not set to any value, a message that the particular cookie has expired is shown.
  • And if the cookie contains the value, it is retrieved using $_COOKIE variable with name of the cookie as its key as shown below for an example.
  • Here the value of cookie username is retrieved and displayed using echo statement.
  • The output is shown below:

  • fig 2

Updating a cookie:

  • To update or modify a cookie value, the way is just use the setcookie() function again to set another value to it.
  • Let us see the following example: We have a previously defined cookie named pwd. It has value pranita@123. Let us modify its value to priyanka@123.
  • Write the following code in index.php page:
  • In the above code we have set the cookie pwd from its value pranita@123 to value priyanka@123 as shown in the following code:
  • Next, it is accessed using $_COOKIE and displayed using the following code:
  • The output is shown below:

  • fig 3

Deleting the cookie:

  • Same as modifying the cookie we don’t have any special way to delete the cookie.
  • To destroy a cookie we just have to use the setcookie() function again and set its expiration time to be in the past.
  • We have created a cookie username at the beginning with 1 hour expiration period. Let us destroy it by purposefully subtracting the 1 hour period from the current time.
  • The code is given below:
  • In the above code we have removed the value of cookie username and purposefully forced the cookie to expire by reducing its expiry time by 1 hour as shown in the statement below:
  • Here, we have subtracted 1hour i.e. 3600 seconds from the current time and made the cookie inaccessible.
  • This is mostly used when the user logs out from the site.
  • The output is shown below:

  • fig 4

Thus we learned to deal with cookies in this PHP Cookies tutorial.


Please enter your comment!
Please enter your name here