开发者

Test for cookies in PHP

What is the best way to tell if someone has cookies enabled in their browser. I tried:

<?php
开发者_StackOverflow社区
        setcookie('cookies','yes',time()+7200);
    if (!isset($_COOKIE['cookies'])) {
        echo '<div class="error" style="float:right;">You must enable cookies and Javascript to use this site.</div>';
    } else {
        echo '';
    }


?>

but sometimes it displays the alert even if cookies are enabled. I only want an alert if cookies are NOT enabled.


The reason that your code doesn't work is because cookies are sent with the request. The code you're trying will work, but setcookie has to be in a different request than the isset call. Try calling a redirect in between calling those 2 functions.


It is because your cookies are set at the same time as your request is sent to the browser. It means that even if setcookie() is executed before the script ends the cookies are set after the browser received the request.

To do in a such way, you would need to redirect to a page with a trivial argument and then check for cookies.

A more flexible solution would be to check in javascript.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜