PHP Cookies - Background
Cookies have been around for quite some time on the internet. They were invented to allow webmaster's to store information about the user and their visit on the user's computer.At first they were feared by the general public because it was believed they were a serious privacy risk. Nowadays nearly everyone has cookies enabled on their browser, partly because there are worse things to worry about and partly because all of the "trustworthy" websites now use cookies.
This lesson will teach you the basics of storing a cookie and retrieving a cookie, as well as explaining the various options you can set with your cookie.
Creating Your First PHP Cookie
When you create a cookie, using the function setcookie, you must specify three arguments. These arguments are setcookie(name, value, expiration):- name: The name of your cookie. You will use this name to later retrieve your cookie, so don't forget it!
- value: The value that is stored in your cookie. Common values are username(string) and last visit(date).
- expiration: The date when the cookie will expire and be deleted. If you do not set this expiration date, then it will be treated as a session cookie and be removed when the browser is restarted.
PHP Code:
<?php
//Calculate 60 days in the future
//seconds * minutes * hours * days + current time
$inTwoMonths = 60 * 60 * 24 * 60 + time();
setcookie('lastVisit', date("G:i - m/d/y"), $inTwoMonths);
?>
Retrieving Your Fresh Cookie
If your cookie hasn't expired yet, let's retrieve it from the user's PC using the aptly named $_COOKIE associative array. The name of your stored cookie is the key and will let you retrieve your stored cookie value!PHP Code:
<?php if(isset($_COOKIE['lastVisit'])) $visit = $_COOKIE['lastVisit']; else echo "You've got some stale cookies!"; echo "Your last visit was - ". $visit; ?>
Display:
Your last visit was - 11:48 - 02/28/08
0 comments:
Post a Comment