Thursday, April 23, 2009

How to set cookie using PHP

PHP provides a function called setcookie(name, value, expire, path, domain) which can be used to set cookies. Here is an example:

$expire=time()+60*60*24*30; setcookie("user", "John Smith", $expire);

This will set the cookie with user name as "John Smith" and cookie will expire in 30 days which have been converted to seconds. The cookie can be retrieved back as follows:

if (isset($_COOKIE["user"]))   echo "Welcome " . $_COOKIE["user"] . "!
"; else echo "Welcome guest!

To delete a cookie use the setcookie function again. When deleting a cookie the expiration time should be in the past. Here it is set 1 hour ago: 

setcookie("user", "", time()-3600);

Remember all PHP cookies should be set in the header before any html tags for them to work properly.

No comments:

Post a Comment