检测是否在PHP中启用了cookie

时间:2012-02-25 21:53:27

标签: php

我正在尝试检测我网页上的用户是否启用了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();
    }
}

4 个答案:

答案 0 :(得分:8)

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

创建两个文件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


更新

这是一个单一的文件解决方案。

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

答案 1 :(得分:1)

HTTP_REFERER对我不起作用,似乎REQUEST_URI就是我需要的。

以下是我最终使用的代码:

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;
            $go_to = $_SESSION['cookie_test_caller'];
            unset( $_SESSION['cookie_test_caller'] );
            header("Location: $go_to");
            exit();
            }
        }
    if( !isset( $_COOKIE['PHPSESSID'] ) ){
        $_SESSION['cookie_test_caller'] = $_SERVER['REQUEST_URI'];
        header('Location: index.php?cookie_test=1');
        exit();
        }
    }
// ------------------------------- //

答案 2 :(得分:0)

之后无需保存原始网址并重定向到该网址。您可以通过AJAX执行透明重定向,但不会触发页面重新加载。它实现起来非常简单。您可以在此处查看我的帖子:https://stackoverflow.com/a/18832817/2784322

答案 3 :(得分:0)

我认为这是最简单的解决方案。不需要单独的文件,如果启用了cookie,则允许您继续使用脚本:

import wx
from wx.lib.pubsub import Publisher
import sys

reload(sys)
sys.setdefaultencoding('cp1252')

########################################################################
class OtherFrame(wx.Frame):

    #----------------------------------------------------------------------
   def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Secondary Frame for showing ResulT",size=(400,400))
        self.panel = OtherPanel(self)


class OtherPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent=parent)
        self.frame = parent

########################################################################
class MainPanel(wx.Panel):
    #----------------------------------------------------------------------
    def __init__(self, parent):
        wx.Panel.__init__(self, parent=parent)
        self.frame = parent


        self.postal_code = wx.TextCtrl(self, value="")
        self.limit = wx.TextCtrl(self,value="")
        showSecondFrame = wx.Button(self, label="Catching")
        showSecondFrame.Bind(wx.EVT_BUTTON, self.ShowFrame)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.postal_code, 0, wx.ALL|wx.CENTER, 5)
        sizer.Add(self.limit, 0, wx.ALL|wx.CENTER, 10)
        sizer.Add(hideBtn, 0, wx.ALL|wx.CENTER, 5)
        self.SetSizer(sizer)

    #----------------------------------------------------------------------
    def ShowFrame(self, event):
        postal_code = self.postal_code.GetValue()
        limit = self.limit.GetValue() 
        new_frame = OtherFrame()
        new_frame.Show()
        print limit, postal_code
        Y = 10
        i=0
        all_data = ['Far Away 1337','Street Dance 101','Necro Lover 152','N0stalgene 689']
        for address in all_data:
            Y += 20
            i += 1

            self.cb = wx.CheckBox(new_frame, label=str(address+"-"+postal_code+"-"+limit), pos=(10,Y))


########################################################################
class MainFrame(wx.Frame):
    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "TEST1NG")
        self.panel = MainPanel(self)
        self.new_frame = OtherFrame()


#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    frame = MainFrame()
    frame.Show()
    app.MainLoop()