在进入网站- PHP,重定向,cookie之前,要有一个用户协议


Make a user agreement before enter site - PHP, Redirect, Cookies

我需要一些帮助与php重定向,cookie等。要指定我想要它做什么,请查看description:

我已经创建了文件:index.php, contact.php, info.php等…我还写入了agecheck。php

当你进入index。php, contact。php, info.php等时,它会重定向到agecheck。php,在那里你有机会点击两个按钮YESNO。如果你点击YES,它会返回到你重定向的前一个页面,如果你点击NO,它会停留在agecheck.php上,并有一个注释说:

你必须年满18岁才能进入网站

但是我也想有cookie,它会记住如果你点击了YES之前,所以你不应该有重定向每次当你进入网站

您可以设置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']);
}
?>

重定向,使用header():

header("Location: agecheck.php");

然后检查哪个按钮被按下,你将不得不使用一些JavaScript:

<script type = "text/javascript">
function yesbutton()
{
window.location.assign("Yourpage.php");
}
function nobutton()
{
document.write("You must be over 18 to view this page");
}
</script>
<input type = "button" onclick = "yesbutton()" value = "yes">
<input type = "button" onclick = "nobutton()" value = "no">

则可以在yesbutton()函数中设置JavaScript cookie。

使用JScript的原因是按钮在客户端,而PHP在服务器端。这意味着它们不能交互

相关文章: