0

我需要一些关于 php 重定向、cookie 等的帮助。要指定我到底想要它做什么,请查看描述:

我创建了文件:index.php、contact.php、info.php 等。我还制作了 agecheck.php

所以我要做什么,当你转到 index.php、contact.php、info.php 等时,它会重定向到 agecheck.php,在那里你有机会点击两个按钮YESNO。如果您单击YES,它会将您返回到您被重定向的上一个页面,如果您单击NO,它将仅停留在 agecheck.php 上,并带有一条说明:

您必须年满 18 岁才能进入该网站。

但是我也希望启用 cookie,它会记住您之前是否单击,因此您不必每次进入站点时都被重定向。

4

2 回答 2

0

您可以设置 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']);
}
?>
于 2013-05-08T09:35:46.130 回答
0

要重定向,请使用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 在服务器端。这意味着他们无法互动。

于 2013-05-08T09:39:36.767 回答