Development Tip

쿠키가 활성화되어 있는지 확인

yourdevel 2020. 11. 21. 09:11
반응형

쿠키가 활성화되어 있는지 확인


나는 자바 스크립트와 세션이 필요한 페이지에서 작업하고 있습니다. 자바 스크립트가 비활성화 된 경우 사용자에게 경고하는 코드가 이미 있습니다. 이제 세션 ID가 쿠키에 저장되어 있으므로 쿠키가 비활성화 된 경우를 처리하고 싶습니다.

몇 가지 아이디어 만 생각했습니다.

  1. 링크 및 양식에 세션 ID 포함
  2. 쿠키가 비활성화 된 경우 쿠키를 활성화해야 함을 사용자에게 경고 (쿠키 비활성화 여부를 감지하는 데 도움이 필요함)

이에 접근하는 가장 좋은 방법은 무엇입니까? 감사

편집하다

링크 된 기사를 바탕으로 나만의 접근 방식을 생각해 내고 공유 할 것이라고 생각했습니다. 다른 사람이 사용할 수있을 수도 있고 비평을받을 수도있을 것입니다. (PHP 세션이라는 쿠키에 저장되어 있다고 가정 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에서는 모든 주요 브라우저에서 지원되는 cookieEnabled 속성에 대한 간단한 테스트를 수행 합니다. 이전 브라우저를 사용하는 경우 쿠키를 설정하고 쿠키가 있는지 확인할 수 있습니다. ( 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에서는 페이지를 새로 고치거나 다른 스크립트로 리디렉션해야하기 때문에 다소 "복잡"합니다. 여기서는 두 가지 스크립트를 사용합니다.

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

그러나 isset ($ _ 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";

동일한 페이지의 로딩 세트에서 쿠키가 설정되어 있는지 확인할 수 없으며 페이지를 다시로드해야합니다.

  • PHP는 서버에서 실행됩니다.
  • 클라이언트의 쿠키.
  • 페이지로드 중에 만 서버로 전송되는 쿠키.
  • 방금 생성 된 쿠키는 아직 서버로 전송되지 않았으며 다음 페이지로드시에만 전송됩니다.

투명하고 깨끗하며 간단한 접근 방식, PHP로 쿠키 가용성을 확인 하고 AJAX 투명 리디렉션 을 활용 하여 페이지 다시로드를 트리거하지 않습니다 . 세션도 필요하지 않습니다.

클라이언트 측 코드 (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 호출은 순수 JavaScript AJAX 호출로 대체 될 수 있습니다.)

서버 측 코드 (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();
    }
}

스크립트가 처음 호출되면 쿠키가 설정되고 스크립트는 브라우저가 자신을 리디렉션하도록 지시합니다. 브라우저는이를 투명하게 수행합니다. AJAX 호출 범위 내에서 수행되기 때문에 페이지 다시로드가 발생하지 않습니다 .

두 번째로 리디렉션에 의해 호출 될 때 쿠키가 수신되면 스크립트가 HTTP 200 (문자열 "true")에 응답하므로 showCookiesMessage함수가 호출됩니다.

스크립트가 두 번째로 호출되고 ( "reload"매개 변수로 식별 됨) 쿠키가 수신되지 않으면 "false"문자열로 HTTP 200에 응답하고 showCookiesMessage함수가 호출됩니다.


Ajax 호출을 할 수 있습니다 ( 참고 :이 솔루션에는 JQuery가 필요합니다) :

example.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

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

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

결과적으로 쿠키 활성화 여부를 보여주는 경고 상자가 나타납니다. 물론 경고 상자를 표시 할 필요는 없습니다. 여기에서 비활성화 된 쿠키를 처리하기 위해 다른 단계를 수행 할 수 있습니다.


자바 스크립트

JavaScript를 사용하여 쿠키를 만들고 존재하는지 확인할 수 있습니다.

//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

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

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

Php

setcookie("testcookie", "testvalue");

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

}

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


it is easy to detect whether the cookies is enabled:

  1. set a cookie.
  2. get the cookie

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

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 common that people dont want to enable cookies.


Here is a very useful and lightweight javascript plugin to accomplish this: 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.


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.

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.

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

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

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

참고URL : https://stackoverflow.com/questions/6663859/check-if-cookies-are-enabled

반응형