PHP and Cookies – Creating, Reading and Writing


Web servers are typically stateless entities. That is to say they serve up web pages without regard to who requested the page and with no knowledge of whether that person has previously requested other pages. This makes it difficult for web based applications to track whether a visitor is new to the site or whether they have visited before and have already logged into a service. Cookies were developed to provide a mechanism to track state in the otherwise stateless world of the web.

Cookies essentially provide a mechanism to store small pieces of data on the computer systems of the visitors to your site. This enables you to maintain the state of a user’s visit to your site so that you can track their movement through the site, or to store information such as their user name and address after they have entered it on one page so that they don’t have to keep re-entering it on different pages.

Before going too far in implementing cookies on your web site it is important to keep in mind that users can disable cookie support in their browsers. You should, therefore, avoid making your site completely dependent on cookies.

Another option for maintaining state is to use PHP Sessions. Cookies and sessions differ in important ways, and which to use depends on your requirements. Continue reading