Making Cookies with PHP
by Bandicoot Marketing on | Posted in Tutorials | 6 comments
I’ve been going nuts over the past month trying to complete a project for a large retail store and it seems like every new request they make requires me to learn something new about PHP. Coding challenges are always great because they lead you to discover new ways to take advantage of what your coding language has to offer. This one is pretty straightforward but great to know.
First we need to set the cookie:
<?php // basic setting // setcookie(name, value, expire, path, domain); $expire = time() + 60 * 60 * 24 * 30; // expires in one month setcookie('visited','yes',$expire); ?>
The above cookie records that someone has already visited the site. It will expire in one month and the path and domain are set automatically if left blank. If you do not include an expiration time, the cookie will only be stored for the current session.
NOTE: Cookies must always be set before anything else, so be sure to place it above the <html> tag at the top of your file.
Here is how you would retrieve a cookie:
<?php // display one cookie with the name "visited" $the_cookie = $_COOKIE['visited']; // see all cookies print_r($_COOKIE); ?>
To delete a cookie we need to take advantage of the expire variable:
<?php // set the cookie to expire one hour in the past $expire = time() - 3600; setcookie('visited', '', $expire); ?>
Resource: PHP: setcookie – Manual
6 comments for “Making Cookies with PHP”