您可以设置 cookie 或使用会话,但如果您的用户浏览器不接受 cookie,这将不起作用。
cookie 的优点是您可以将其设置为在用户关闭浏览器后继续存在(但用户可以禁用此行为)
会话(还要求用户允许 cookie)
<?php
// This check must be at the top of every page, e.g. through an include
session_start();
if(!isset($_SESSION['agecheck']) || !$_SESSION['agecheck']){
$_SESSION['agecheck_ref'] = $_SERVER['REQUEST_URI'];
header("Location: http://your.site/agecheck.php");
die();
}
?>
<?php
// You need to set the session variable in agecheck.php
session_start();
if($age >= 18){
$_SESSION['agecheck'] = true;
if(!isset($_SESSION['agecheck_ref'])) {
$_SESSION['agecheck_ref'] = "/";
}
header("Location: http://your.site" . $_SESSION['agecheck_ref']);
}
?>
或与 cookie 类似,您可以将其设置为持续更长时间
<?php
// This check must be at the top of every page, e.g. through an include
session_start();
if(!isset($_COOKIE['agecheck']) || $_COOKIE['agecheck'] != "true"){
$_SESSION['agecheck_ref'] = $_SERVER['REQUEST_URI'];
header("Location: http://your.site/agecheck.php");
die();
}
?>
<?php
// You need to set the cookie in agecheck.php
session_start();
if($age >= 18){
setcookie("agecheck", "true", time()+60*60*24*90); // Remember answer for 90 days
if(!isset($_SESSION['agecheck_ref'])) {
$_SESSION['agecheck_ref'] = "/";
}
header("Location: http://your.site" . $_SESSION['agecheck_ref']);
}
?>