我试图检测我的页面上的用户是否启用了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();
}
}
Run Code Online (Sandbox Code Playgroud)
我认为最好制作一个文件集cookie并重定向到另一个文件.然后下一个文件可以检查该值并确定是否启用了cookie.查看示例.
创建两个文件,cookiechecker.php
和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");
Run Code Online (Sandbox Code Playgroud)
和
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; ?>
Run Code Online (Sandbox Code Playgroud)
cookiechecker.php
在浏览器中加载它会告诉cookie is working
.用命令行调用它curl
.它会说,cookie is not working
这是一个单一文件解决方案.
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");
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
18956 次 |
最近记录: |