sehummel
sehummel

Reputation: 5568

Test for cookies in PHP

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

<?php

        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.

Upvotes: 1

Views: 212

Answers (2)

Boris Gu&#233;ry
Boris Gu&#233;ry

Reputation: 47614

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.

Upvotes: 2

ryeguy
ryeguy

Reputation: 66891

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.

Upvotes: 6

Related Questions