Javascript 检查 cookie 是否已启用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6663859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:42:32  来源:igfitidea点击:

Check if cookies are enabled

phpjavascriptsession-cookies

提问by steveo225

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.

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

I have thought of just a couple ideas:

我想到了几个想法:

  1. Embedding the session id in the links and forms
  2. Warn the user they must enable cookies if they are disabled (would need help detecting if cookies are disabled)
  1. 在链接和表单中嵌入会话 ID
  2. 警告用户,如果 cookie 被禁用,他们必须启用 cookie(需要帮助检测 cookie 是否被禁用)

What is the best way to approach this? Thanks

解决这个问题的最佳方法是什么?谢谢

EDIT

编辑

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)

根据链接的文章,我想出了我自己的方法,并认为我会分享,其他人可能会使用它,也许我会得到一些批评。(假设您的 PHP 会话存储在名为 的 cookie 中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>

回答by Sascha Galley

JavaScript

JavaScript

In JavaScript you simple test for the cookieEnabledproperty, 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):

在 JavaScript 中,您可以简单测试cookieEnabled属性,所有主要浏览器都支持该属性。如果您使用较旧的浏览器,您可以设置一个 cookie 并检查它是否存在。(借自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;

PHP

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:

在 PHP 中,它相当“复杂”,因为您必须刷新页面或重定向到另一个脚本。这里我将使用两个脚本:

somescript.php

一些脚本.php

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

check.php

检查.php

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

回答by misza

But to check whether cookies are enabled using isset($_COOKIE["cookie"]) you have to refresh. Im doing it ths way (with sessions based on cookies :)

但是要检查是否使用 isset($_COOKIE["cookie"]) 启用了 cookie,您必须刷新。我是这样做的(使用基于 cookie 的会话 :)

session_start();
$a = session_id();
session_destroy();

session_start();
$b = session_id();
session_destroy();

if ($a == $b)
    echo"Cookies ON";
else
    echo"Cookies OFF";

回答by Codebeat

Answer on an old question, this new post is posted on April the 4th 2013

回答一个老问题,这个新帖子发布于 2013 年 4 月 4 日

To complete the answer of @misza, here a advanced method to check if cookies are enabled without page reloading. The problem with @misza is that it not always work when the php ini setting session.use_cookiesis not true. Also the solution does not check if a session is already started.

为了完成@misza 的回答,这里有一种高级方法来检查 cookie 是否已启用而无需重新加载页面。@misza 的问题在于,当 php ini 设置session.use_cookies不正确时,它并不总是有效。此外,该解决方案不会检查会话是否已启动。

I made this function and test it many times with in different situations and does the job very well.

我制作了这个功能并在不同情况下对其进行了多次测试,并且做得很好。

    function suGetClientCookiesEnabled() // Test if browser has cookies enabled
    {
      // Avoid overhead, if already tested, return it
      if( defined( 'SU_CLIENT_COOKIES_ENABLED' ))
       { return SU_CLIENT_COOKIES_ENABLED; }

      $bIni = ini_get( 'session.use_cookies' ); 
      ini_set( 'session.use_cookies', 1 ); 

      $a = session_id();
      $bWasStarted = ( is_string( $a ) && strlen( $a ));
      if( !$bWasStarted )
      {
        @session_start();
        $a = session_id();
      }

   // Make a copy of current session data
  $aSesDat = (isset( $_SESSION ))?$_SESSION:array();
   // Now we destroy the session and we lost the data but not the session id 
   // when cookies are enabled. We restore the data later. 
  @session_destroy(); 
   // Restart it
  @session_start();

   // Restore copy
  $_SESSION = $aSesDat;

   // If no cookies are enabled, the session differs from first session start
  $b = session_id();
  if( !$bWasStarted )
   { // If not was started, write data to the session container to avoid data loss
     @session_write_close(); 
   }

   // When no cookies are enabled, $a and $b are not the same
  $b = ($a === $b);
  define( 'SU_CLIENT_COOKIES_ENABLED', $b );

  if( !$bIni )
   { @ini_set( 'session.use_cookies', 0 ); }

  //echo $b?'1':'0';
  return $b;
    }

Usage:

用法:

if( suGetClientCookiesEnabled())
 { echo 'Cookies are enabled!'; }
else { echo 'Cookies are NOT enabled!'; }

Important note:The function temporarily modify the ini setting of PHP when it not has the correct setting and restore it when it was not enabled. This is only to test if cookies are enabled. It can get go wrong when you start a session and the php ini setting session.use_cookies has an incorrect value. To be sure that the session is working correctly, check and/or set it before start a session, for example:

重要提示:该功能在没有正确设置时临时修改 PHP 的 ini 设置,并在未启用时恢复它。这仅用于测试是否启用了 cookie。当您启动会话并且 php ini 设置 session.use_cookies 的值不正确时,它可能会出错。为确保会话正常工作,请在开始会话之前检查和/或设置它,例如:

   if( suGetClientCookiesEnabled())
     { 
       echo 'Cookies are enabled!'; 
       ini_set( 'session.use_cookies', 1 ); 
       echo 'Starting session';
       @start_session(); 

     }
    else { echo 'Cookies are NOT enabled!'; }

回答by zibilico

A transparent, clean and simple approach, checking cookies availability with PHPand taking advantage of AJAXtransparent redirection, hence not triggering a page reload. It doesn't require sessions either.

一种透明、干净和简单的方法,使用PHP检查 cookie 的可用性并利用AJAX透明重定向,因此不会触发页面重新加载。它也不需要会话。

Client-side code (JavaScript)

客户端代码 (JavaScript)

function showCookiesMessage(cookiesEnabled) {
    if (cookiesEnabled == 'true')
        alert('Cookies enabled');
    else
        alert('Cookies disabled');
}

$(document).ready(function() {
    var jqxhr = $.get('/cookiesEnabled.php');
    jqxhr.done(showCookiesMessage);
});

(JQuery AJAX call can be replaced with pure JavaScript AJAX call)

(JQuery AJAX 调用可以替换为纯 JavaScript AJAX 调用)

Server-side code (PHP)

服务器端代码 (PHP)

if (isset($_COOKIE['cookieCheck'])) {
    echo 'true';
} else {
    if (isset($_GET['reload'])) {
        echo 'false';
    } else {
        setcookie('cookieCheck', '1', time() + 60);
        header('Location: ' . $_SERVER['PHP_SELF'] . '?reload');
        exit();
    }
}

First time the script is called, the cookie is set and the script tells the browser to redirect to itself. The browser does it transparently. No page reload takes place because it's done within an AJAX call scope.

第一次调用脚本时,cookie 被设置,脚本告诉浏览器重定向到它自己。浏览器是透明的。没有页面重新加载发生,因为它是在 AJAX 调用范围内完成的

The second time, when called by redirection, if the cookie is received, the script responds an HTTP 200 (with string "true"), hence the showCookiesMessagefunction is called.

第二次,当通过重定向调用时,如果收到 cookie,脚本会响应 HTTP 200(带有字符串“true”),因此showCookiesMessage调用该函数。

If the script is called for the second time (identified by the "reload" parameter) and the cookie is not received, it responds an HTTP 200 with string "false" -and the showCookiesMessagefunction gets called.

如果第二次调用脚本(由“reload”参数标识)并且没有收到 cookie,它会响应一个带有字符串“false”的 HTTP 200 - 并且该showCookiesMessage函数被调用。

回答by drfunjohn

You cannot in the same page's loading set and check if cookies is set you must perform reload page:

您不能在同一页面的加载集中检查是否设置了 cookie,您必须执行重新加载页面:

  • PHP run at Server;
  • cookies at client.
  • cookies sent to server only during loading of a page.
  • Just created cookies have not been sent to server yet and will be sent only at next load of the page.
  • PHP 运行在服务器端;
  • 客户端的cookies。
  • cookie 仅在页面加载期间发送到服务器。
  • 刚刚创建的 cookie 尚未发送到服务器,只会在页面下次加载时发送。

回答by Black

You can make an Ajax Call (Note: This solution requires JQuery):

您可以进行 Ajax 调用(注意:此解决方案需要 JQuery):

example.php

例子.php

<?php
    setcookie('CookieEnabledTest', 'check', time()+3600);
?>

<script type="text/javascript">

    CookieCheck();

    function CookieCheck()
    {
        $.post
        (
            'ajax.php',
            {
                cmd: 'cookieCheck'
            },
            function (returned_data, status)
            {
                if (status === "success")
                {
                    if (returned_data === "enabled")
                    {
                        alert ("Cookies are activated.");
                    }
                    else
                    {
                        alert ("Cookies are not activated.");
                    }
                }
            }
        );
    }
</script>

ajax.php

ajax.php

$cmd = filter_input(INPUT_POST, "cmd");

if ( isset( $cmd ) && $cmd == "cookieCheck" )
{
    echo (isset($_COOKIE['CookieEnabledTest']) && $_COOKIE['CookieEnabledTest']=='check') ? 'enabled' : 'disabled';
}

As result an alert box appears which shows wheter cookies are enabled or not. Of course you don't have to show an alert box, from here you can take other steps to deal with deactivated cookies.

结果会出现一个警告框,显示是否启用了 cookie。当然,您不必显示警告框,从这里您可以采取其他步骤来处理停用的 cookie。

回答by Tomgrohl

JavaScript

JavaScript

You could create a cookie using JavaScript and check if it exists:

您可以使用 JavaScript 创建一个 cookie 并检查它是否存在:

//Set a Cookie`
document.cookie="testcookie"`

//Check if cookie exists`
cookiesEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false`

Or you could use a jQuery Cookie plugin

或者你可以使用jQuery Cookie 插件

//Set a Cookie`
$.cookie("testcookie", "testvalue")

//Check if cookie exists`
cookiesEnabled=( $.cookie("testcookie") ) ? true : false`

Php

php

setcookie("testcookie", "testvalue");

if( isset( $_COOKIE['testcookie'] ) ) {

}

Not sure if the Php will work as I'm unable to test it.

不确定 Php 是否可以工作,因为我无法对其进行测试。

回答by James.Xu

it is easy to detect whether the cookies is enabled:

很容易检测是否启用了 cookie:

  1. set a cookie.
  2. get the cookie
  1. 设置一个cookie。
  2. 拿到饼干

if you can get the cookie you set, the cookieis enabled, otherwise not.

如果您可以获取您设置的 cookie,cookie则启用该 cookie ,否则不启用。

BTW: it is a bad idea to Embedding the session id in the links and forms, it is bad for SEO. In my opinion, it is not very commonthat people dont want to enable cookies.

顺便说一句:这是一个坏主意Embedding the session id in the links and forms,这对 SEO 不利。在我看来,人们不想启用 cookie 的情况并不常见

回答by Harm

Cookies are Client-side and cannot be tested properly using PHP. That's the baseline and every solution is a wrap-around for this problem.

Cookie 是客户端,无法使用 PHP 正确测试。这是基线,每个解决方案都是针对这个问题的一个总结。

Meaning if you are looking a solution for your cookie problem, you are on the wrong way. Don'y use PHP, use a client language like Javascript.

这意味着如果您正在寻找 cookie 问题的解决方案,那么您就走错了路。不要使用 PHP,使用像 Javascript 这样的客户端语言。

Can you use cookies using PHP? Yes, but you have to reload to make the settings to PHP 'visible'.

您可以使用 PHP 使用 cookie 吗?是的,但您必须重新加载才能使 PHP 设置“可见”。

For instance: Is a test possible to see if the browser can set Cookies with plain PHP'. The only correct answer is 'NO'.

例如:是否可以进行测试以查看浏览器是否可以使用纯 PHP 设置 Cookie。唯一正确的答案是“不”。

Can you read an already set Cookie: 'YES' use the predefined $_COOKIE (A copy of the settings before you started PHP-App).

您能否读取已设置的 Cookie: 'YES' 使用预定义的 $_COOKIE(启动 PHP-App 之前的设置副本)。

回答by Grant

Here is a very useful and lightweight javascript plugin to accomplish this: js-cookie

这是一个非常有用且轻量级的 javascript 插件来完成此任务:js-cookie

Cookies.set('cookieName', 'Value');
      setTimeout(function(){
        var cookieValue =  Cookies.get('cookieName');
        if(cookieValue){
           console.log("Test Cookie is set!");
        } else {
           document.write('<p>Sorry, but cookies must be enabled</p>');
        }
        Cookies.remove('cookieName');
      }, 1000);

Works in all browsers, accepts any character.

适用于所有浏览器,接受任何字符。