Cooking cookies in PHP

Websites are primarily created through HTML programming. A web page created in HTML is a dumb entity; it does not know who fetched it for browsing and where that website visitor was located. The most important reason behind the anonymous nature of this entire web surfing experience is the protocol being used for sending requests and receiving responses from the webserver. This protocol is known as HTTP or hypertext transfer protocol. This protocol is a stateless protocol, which means it will treat each request and its response as an independent transaction. So if there were two requests sent one after another by the same user and for the web pages of the same website, then each request will be treated as coming from two different users.

This stateless nature was pretty restricting for the website owners since they could not determine who visited their website and from which place their website got most hits. Cookie turned out to be a near perfect solution which enabled each user and its location to be identified. If your mouth already started watering from the name of it then let me disappoint you a bit. These cookies are not those bakery created delicacies but small files located in the website visitor’s computer, which stored all the vital details about the visitors like username, IP address and even operating system. Now the use of cookies has expanded, it is used by the developers to track down the browsing habits of the visitors, which can help developers customize their website as per the preferences of the visitors.

Cookies can be set in PHP by using setcookie() function. The syntax of the setcookie() function is as follows,

Setcookie(‘cookiename’, ‘value’, ‘expiry time’, ‘path’, ‘domain’, ‘secure connection’);


A short description of all the parameters is as given below,

Cookiename: This is a user defined name given to the cookie being created.

Value: value normally contains username of the visitor.

Expiry time: This is the time duration, in seconds, after which cookie will expire.

Path: This is an optional parameter, which indicates the directory path of the visitor’s computers, where the cookie file will be saved.

Domain: This indicates the domain name of the cookie.

Secure connection: This is again an optional parameter which is meant for secured web transaction.

Cookies completely changed the game of internet browsing, but there are some pitfalls also associated with it. People with malicious intent can always get unauthorized access to the cookie file and lay their hands on sensitive information, therefore there is a disable cookie feature in nearly all the browsers, which can help visitors protect their privacy.

Author: ucavik