Creating And Retrieving Cookies In PHP

by Hiroshi on June 23, 2008

in Cookies, isset

Cookies were invented to allow webmaster’s to store information about the user and their visit or other information on the user’s computer. Cookies are not privacy risk. All of the “trustworthy” websites use cookies.

Creating Cookie – Last Visit Script

<?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 Cookie

If your cookie hasn’t expired yet, you can retrieve it from the user’s PC using the named $_COOKIE associative array. The name of your stored cookie is the key and will let you retrieve your stored cookie value!

<?php
if(isset($_COOKIE['lastVisit']))
	$visit = $_COOKIE['lastVisit'];
else
	echo "You've got some stale cookies!";
 
echo "Your last visit was - ". $visit;
?>

Related Posts

Previous post:

Next post: