Making Cookies with PHP
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



Good basic article. I would suggest that if you are going to print arrays to the browser, you surround them in pre tags, like this:
That will make it a lot easier to read.
Oops, it replaced the with the html equivalent…
Learning new coding language is good but sharing it with everyone is truly generous and this one which helps you to make Cookies with PHP was really a great discovery!! The tip about the cookie’s expiration time and the reminder about its placement were very helpful and found it very useful information! The tip about deleting it was also new information for me!!
Great beginners guide!
Cheers
Learning new coding language is good but sharing it with everyone is truly generous and this one which helps you to make Cookies with PHP was really a great discovery!! The tip about the cookie’s expiration time and the reminder about its placement were very helpful and found it very useful information! The tip about deleting it was also new information for me!!