我需要一些关于php重定向,cookie等的帮助。 要指定我想要它做什么,请看一下描述:
我创建了文件:index.php,contact.php,info.php等。 我也做了agecheck.php
所以我知道它,当你去index.php,contact.php,info.php等,然后它将重定向到agecheck.php,你有机会点击两个按钮是或否。如果您点击是,它会返回您重定向的上一页,如果您单击否,它将保留在agecheck.php上并附上一条注释表示:
您必须年满18岁才能进入该网站。
但我也希望有cookie,如果您之前点击了 YES ,则会记得,所以每次进入网站时都不必重定向。
答案 0 :(得分: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']);
}
?>
答案 1 :(得分: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位于服务器端。这意味着他们无法互动。