I've created a php script to control the timing of a popup window. I only want to popup to display once per 60 seconds. The script sets a cookie the first time the user visits the page, and then for subsequent visits the script checks the cookie and only activates the popup if the cookie has expired. The popup is controlled by the variable $_SESSION['activate_popup'].
The scripts works as intended in all cases except for the when the user visits the page for the first time. The cookie is empty and so it should set the cookie and activate the popup in condition 1. Instead, it sets the cookie in condition 1 and displays the output in condition 2.
$GLOBALS['popup_output'] .= '<!-- begin popup -->';
$domain = 'brocktonvilla.com';
$expiration = time() + 60;
$time_until_expires = $_COOKIE['rc_popuup2'] - time();
$GLOBALS['popup_output'] .= '<!-- time until expires: ' . $time_until_expires . ' sec -->';
/* 1 */ if ( empty($_COOKIE['rc_popuup2']) ) { // if cookie has not been set
setcookie('rc_popuup2', $expiration, $expiration, '/', $domain ); // set cookie with value of cookie equals expiration time
$_SESSION['activate_popup'] = 'yes'; // activate the popup
$GLOBALS['popup_output'] .= '<!-- cookie empty => show popup & set cookie -->';
}
/* 2 */ elseif ( $_COOKIE['rc_popuup2'] > time() ) { // cookie has been set and cookie expiration is greater than current time
$_SESSION['activate_popup'] = 'no'; // do not activate popup
$GLOBALS['popup_output'] .= '<!-- cookie set and not expired => do not show popup -->';
}
/* 3 */ elseif ( $_COOKIE['rc_popuup2'] < time() ) { // cookie has been set and cookie expiration is less than current time
$_SESSION['activate_popup'] = 'yes'; // activate the popup
setcookie('rc_popuup2', $expiration, $expiration, '/', $domain ); // reset cookie with value of cookie equals expiration time
$GLOBALS['popup_output'] .= '<!-- cookie set but has expired => show popup & reset cookie -->';
}
You can see the script in action here http://www.brocktonvilla.com/. Search the source code "begin popup" and you will see that the cookie has both been set in condition 1 and displays the output in condition 2 the first time you visit the page.