检查是否启用了cookie

编程入门 行业动态 更新时间:2024-10-23 22:27:45
本文介绍了检查是否启用了cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在处理一个需要JavaScript和会话的页面.我已经有代码来警告用户是否禁用了javascript.现在,我想处理禁用cookie的情况,因为会话ID存储在cookie中.

I am working on a page that requires javascript and sessions. I already have code to warn the user if javascript is disabled. Now, I want to handle the case where cookies are disabled, as the session id is stored in cookies.

我想到的只是几个主意:

I have thought of just a couple ideas:

  • 将会话ID嵌入链接和表单中
  • 警告用户必须禁用cookie(如果需要禁用cookie,这将需要帮助,以检测cookie是否被禁用)
  • 解决此问题的最佳方法是什么?谢谢

    What is the best way to approach this? Thanks

    编辑

    基于链接的文章,我想出了自己的方法,并认为我会分享,其他人也许可以使用它,也许我会得到一些批评. (假设您的PHP会话存储在名为PHPSESSID的cookie中)

    Based on the articles linked, I came up with my own approach and thought I would share, somebody else might be able to use it, maybe I will get a few critiques. (Assumes your PHP session stores in a cookie named PHPSESSID)

    <div id="form" style="display:none">Content goes here</div> <noscript>Sorry, but Javascript is required</noscript> <script type="text/javascript"><!-- if(document.cookie.indexOf('PHPSESSID')!=-1) document.getElementById('form').style.display=''; else document.write('<p>Sorry, but cookies must be enabled</p>'); --></script>

    推荐答案

    JavaScript

    在JavaScript中,您可以对 cookieEnabled 属性进行简单测试.主要浏览器.如果您使用的是较旧的浏览器,则可以设置Cookie并检查其是否存在. (从 Modernizer 借用):

    JavaScript

    In JavaScript you simple test for the cookieEnabled property, which is supported in all major browsers. If you deal with an older browser, you can set a cookie and check if it exists. (borrowed from Modernizer):

    if (navigator.cookieEnabled) return true; // set and read cookie document.cookie = "cookietest=1"; var ret = document.cookie.indexOf("cookietest=") != -1; // delete cookie document.cookie = "cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT"; return ret;

    • Modernizer cookie检查提交
    • 检查是否已启用Cookie
      • Modernizer cookie check commit
      • Checking if Cookies are Enabled
      • 在PHP中,它相当复杂",因为您必须刷新页面或重定向到另一个脚本.在这里,我将使用两个脚本:

        In PHP it is rather "complicated" since you have to refresh the page or redirect to another script. Here I will use two scripts:

        somescript.php

        <?php session_start(); setcookie('foo', 'bar', time()+3600); header("location: check.php");

        check.php

        <?php echo (isset($_COOKIE['foo']) && $_COOKIE['foo']=='bar') ? 'enabled' : 'disabled';

        • 检测是否Cookie已通过PHP启用
        • PHP和Cookies,很好的搭配!
          • Detecting if the cookies are enabled with PHP
          • PHP and Cookies, A Good Mix!

    更多推荐

    检查是否启用了cookie

    本文发布于:2023-11-01 01:22:27,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1547835.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:cookie

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!