我创建了一个 php 脚本来控制弹出窗口的时间。我只想每 60 秒弹出一次。该脚本在用户第一次访问该页面时设置一个 cookie,然后对于后续访问,该脚本会检查该 cookie,并且仅在 cookie 过期时才激活弹出窗口。弹出窗口由变量 $_SESSION['activate_popup'] 控制。
脚本在所有情况下都按预期工作,但用户第一次访问页面时除外。cookie 是空的,因此它应该在条件 1 中设置 cookie 并激活弹出窗口。相反,它在条件 1 中设置 cookie 并在条件 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 -->';
}
您可以在此处查看运行中的脚本http://www.brocktonvilla.com/。搜索源代码“begin popup”,你会看到cookie已经被设置为条件1,并在你第一次访问页面时显示条件2的输出。