Cookies are elements that allow a website to leave information on a visitor’s internet browser for a given period of time and access it later time when the visitor comes back to the website. Cookies are very useful in the case of authentication protocols when you want to “remember” a visitor, for example to keep him logged in for a given period of time even during the time his session has been terminated and to save him the trouble of having to login multiple times.
1. Creating a cookie in PHP
To create a PHP cookie, use the function setcookie() and the syntax is as follows:
setcookie(name_of_cookie, value_of_cookie, expiration_time) ,
Where name_of_cookie is a string, which indentifies the cookie, value_of_cookie, is the value of this cookie (also a string). Expiration_time on the other hand, is the time at which the cookie will expire expressed in the number of seconds from the current time.
2. Reading a PHP cookie
Upon setting a cookie, you will need to be able to retrieve it. You can do this by using the global array variable $_COOKIE, whose indexes are the cookies’ names.
3. Checking for a set cookie
To ascertain the existence of a cookie in PHP, the expression isset($_COOKIE[name_of_cookie]) is used and returns TRUE if the cookie has been set and FALSE otherwise.
4. Destroying a PHP cookie
To destroy a PHP cookie, all you need to do is set the expiration time to the past. Below is a PHP syntax example:
setcookie(name_of_cookie, value_of_cookie, time()-1)
5. PHP cookies Security issues in authentication protocols
You may want to allow a user to remain logged in for a certain period of time. To achieve this, you must set a cookie, which will contain the identity of this user, for instance his username and a way to verify that this user has the permission to log into the requested account. In order to achieve the latter, one may be tempted to store the user’s password and compare it to the corresponding data in the database. Unfortunately, with this approach, an adverse party who will gain unauthorized access to your visitor’s account might intercept the cookie.
A solution to this problem is to encrypt the data stored in your cookie so that it will not be decipherable. It is easy to achieve this using any encryption method of your choice with the idea that the PHP script will decrypt the cookie and compare the user’s password with the information stored in the database.
In addition, it is best that you encrypt the information both in your database (e.g. passwords) and within your user’s cookies. In order to do this, PHP language proposes you to use the crypt() function achieve a one-way encryption.