我正在尝试检测我的页面上的用户是否启用了 cookie。以下代码执行检查,但是,我不知道如何将用户重定向到他们来自的页面。
该脚本启动一个会话并检查是否已检查 cookie。如果没有,它会将用户重定向到测试页面,并且由于我在第一页中调用了 session_start(),因此如果用户代理启用了 cookie,我应该会看到 PHPSESSID cookie。
问题是,这个脚本可能会从我网站的任何页面调用,我必须将它们重定向回他们选择的页面,比如index.php?page=news&postid=4。
session_start();
// Check if client accepts cookies //
if (!isset($_SESSION['cookies_ok'])) {
if (isset($_GET['cookie_test'])) {
if (!isset($_COOKIE['PHPSESSID'])) {
die('Cookies are disabled');
} else {
$_SESSION['cookies_ok'] = true;
header(-------- - ? ? ? ? ? -------- -);
exit();
}
}
if (!isset($_COOKIE['PHPSESSID'])) {
header('Location: index.php?cookie_test=1');
exit();
}
}
我认为最好让一个文件设置cookie并重定向到另一个文件。然后下一个文件可以检查该值并确定cookie是否启用。请参阅示例。
创建两个文件,cookiechecker.php
and stat.php
// cookiechecker.php
// save the referrer in session. if cookie works we can get back to it later.
session_start();
$_SESSION['page'] = $_SERVER['HTTP_REFERER'];
// setting cookie to test
setcookie('foo', 'bar', time()+3600);
header("location: stat.php");
and
stat.php
<?php if(isset($_COOKIE['foo']) && $_COOKIE['foo']=='bar'):
// cookie is working
session_start();
// get back to our old page
header("location: {$_SESSION['page']}");
else: // show the message ?>
cookie is not working
<? endif; ?>
Load cookiechecker.php
在浏览器中它会告诉cookie is working
。使用命令行调用它,例如curl
。它会说,cookie is not working
Update
这是一个单文件解决方案。
session_start();
if (isset($_GET['check']) && $_GET['check'] == true) {
if (isset($_COOKIE['foo']) && $_COOKIE['foo'] == 'bar') {
// cookie is working
// get back to our old page
header("location: {$_SESSION['page']}");
} else {
// show the message "cookie is not working"
}
} else {
// save the referrer in session. if cookie works we can get back to it later.
$_SESSION['page'] = $_SERVER['HTTP_REFERER'];
// set a cookie to test
setcookie('foo', 'bar', time() + 3600);
// redirecting to the same page to check
header("location: {$_SERVER['PHP_SELF']}?check=true");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)