且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检测是否在PHP中启用了cookie

更新时间:2023-11-28 08:40:22

我认为使一个文件集cookie并重定向到另一个文件更好.然后,下一个文件可以检查该值并确定是否启用了cookie.参见示例.

I think its better to make one file set cookie and redirect to another file. Then the next file can check the value and determine if cookie is enabled. See the example.

创建两个文件cookiechecker.phpstat.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");

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; ?>

在浏览器中加载cookiechecker.php,它将告诉cookie is working.用curl之类的命令行调用它.会说,cookie is not working

Load cookiechecker.php in browser it'll tell cookie is working. Call it with command line like curl. It'll say, cookie is not working

这是一个文件解决方案.

Here is a single file solution.

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");
}