02 of 04

Setting and Retrieving the Cookie

<?php if(isset($_COOKIE['AboutVisit']))

{

$last = $_COOKIE['AboutVisit']; }



In the first part of the code, we check to see if a cookie is set. If our cookie (named AboutVisit) is set, we retrieve it and assign it to the variable $last. It is important that we do this before we set the cookie, otherwise, we will overwrite the old date before we ever see it.

$year = 31536000 + time() ;

//this adds one year to the current time, for the cookie expiration

setcookie(AboutVisit, time (), $year) ;





Next, we create a variable called $ year. This adds one year to the current date, by adding 31,536,000 seconds (60 seconds * 60 minutes * 24 hours * 365 days.) We use this as the new cookie's expiration date. We then set our new cookie to be the current time. We must be sure when we set a cookie that it is the first thing sent to the browser or it will not work. Any text, HTML, or even a page title will make it not work. These things should all follow the cookie.​