Or Weinberger
Or Weinberger

Reputation: 7472

PHP Cookie not working

I have the following code:

    if ($_COOKIE['lightbox'] != "1") {
        setcookie("lightbox", "1", time()+3600);
        echo("
        <script type='text/javascript'>
        if (window.addEventListener) { // Mozilla, Netscape, Firefox
            window.addEventListener('load', WindowLoad2, false);
        } else if (window.attachEvent) { // IE
            window.attachEvent('onload', WindowLoad2);
        }

        function WindowLoad2(event) {
            displayLightbox();
        }
        </script>
       ");

    }

What I'm basically trying to accomplish it to run displayLightbox() only once for each user by using a cookie. For some reason, I'm getting it for each page I'm going to on the website, except for when I CTRL+F5 the page. After using ctrl+f5 I no longer get the lightbox. Any ideas?

Upvotes: 0

Views: 608

Answers (1)

Abhay
Abhay

Reputation: 6645

It seems the first time when your cookie isn't set, the event is added to your window (unless you do a CTRL+F5) and hence on every page-load, it invokes displayLightbox().Try cancelling the event in the ELSE part of your IF.

Alternatively, try changing your JS code to this:

if ($_COOKIE['lightbox'] != "1") {
    setcookie("lightbox", "1", time()+3600);
    echo("
        <script type='text/javascript'>
        displayLightbox();
        </script>
    ");
}

Hope this helps.

Upvotes: 1

Related Questions