PHP and Cookies; a good mix!
(Page 2 out of 5)Using cookies in PHP is extremely easy. In fact, there is nothing to it, because of PHP's inbuilt setcookie() function. Have a look at the documentation, and then try the following example:
// Set a cookie
// Cookie name: name
// Cookie value: Dennis Pallett
// Cookie expire: in 24 hours
setcookie ('name', 'Dennis Pallett', time() + (60*60*24));
?>
If you run the code above, then a cookie will be set. That's all. The cookie name and value are pretty obvious. The cookie expire is when the cookie expires, or goes away. Simply use the time() function and add the number of seconds you want to have the cookie available to it. In the example I added 60*60*24=86400 seconds, or 24 hours.
If you have looked at the documentation, you probably noticed there are additional arguments. As the documentation says, the path is to limit a cookie to a specific path on your web server. This is often used when you run multiple instances of the same script in separate directories. You can safely omit this argument when it doesn't matter if the cookie is available site-wide.
There is also the domain argument. This can be used to limit the cookie to a specific sub-domain, e.g. test.example.com. You can also safely ignore this argument, or set it to .example.com (note the beginning period, this is essential!).
Finally, there is also the secure argument. This argument is only used for cookies that are sent over a secure HTTPS connection (SSL). Just ignore this argument, unless you're working with a secure connection.
One thing that should be mentioned is that cookies must be set, before you display any HTML/text. It's probably best if you turn on output buffering by putting ob_start() at the top of your page.
Now that you have set a cookie, you probably want to retrieve the value as well. After all, that is the whole point of using cookies. Thankfully, as PHP is ever so easy, you can retrieve the same way as you retrieve a GET value. See the following example to retrieve the value of the previous example:
echo 'Your name is ' . $_COOKIE['name'];
?>
This should print "Your name is Dennis Pallett". There's nothing more to it. It's just that easy!
Finally, one thing you probably want to do as well is remove cookies. This is as easy as setting them. Simply change the value of the cookie to FALSE, and change the expire date to -3000 seconds. See the following example:
setcookie ('name', FALSE, time()-1000);
?>
February 16th, 2006 at 3:09 pm
This site is very helpful to me.
I expect more examples about session and cookies from this site.
Thanks a lot.