BeWebmaster

Cookies how to in PHP

Ad

Cookies are a very useful mechanism to remember information. HTTP protocol is stateless protocol that is, once a page is requested by the client and served by the server, no information is kept. That is where cookies come into the scene. Cookies allow you to store information on the user’s hard disk.

When dealing with cookies in PHP you have to remember three things:

  1. Setting and deleting a cookie before any output to the web browser is sent.
  2. In order to access a cookie information you must refresh the page
  3. A cookie can only be access either from the page it has set it or from all the pages in the sub folder from where the cookie has been set. More on this later.

Setting a cookie in PHP

Setting a cookie in PHP is very simple. Just use the setcookie command before any output to the web browser is sent.

<?php
setcookie("uname", "Gaetano", time()+36000);
?>

In this example three a cookie called uname is being set up. The value of uname will be “Gaetano”. The other parameter sets the value of the expiration date. Using the function time(), you get the current UNIX time stamp. I have added 36000 seconds to the UNIX time stamp so that the expiration time of the uname cookie will be of 10 hours.

Accessing a cookie

Accessing a cookie in PHP is very simple. You can get the cookie value using the $_COOKIE[] associative array. The key to use is the cookie name. The example below illustrates how to do this.

<?php
echo $_COOKIE[‘uname’]; //this will print Gaetano
?>

Deleting a cookie

In order to delete a cookie, use the setcookie function to set the expiry date to an hour ago. The cookie will be automatically deleted from the user’s hard disk.

<?php
setcookie("uname", "", time() - 3600);
?>

Conclusion

More snippets and example can be found at http://www.snippetcollection.com

THE END