Search code examples
phpif-statementcookiessetcookie

Using Cookie Expire with IF and ELSE PHP, echo not working on ELSE


Why?

I'm attempting to setup an Adword Campaign with my WordPress website, pretty easy stuff but I want to be able to SWITCH contact forms depending if they visited the site using AdWords or Bing/Google SERPS.

So the idea is that if they visit https://example.com/landing-page/ they will reach a page with different contact numbers and email form that has a title indicating that they have come from Adwords, all straight forward, but then, if they click the menu bar away from the landing page, they will get standard numbers and standard email forms, which makes the tracking process a little bit harder.

Setting the temporary cookie

So by using custom WordPress page template files, and when a visitor visits the landing page, it sets a cookie using:

<?php
    // 60 Seconds, live environment set to 6000 (1 hour)
    $date_of_expiry = time() + 60 ;
    setcookie( "adwords-customer", "adwords-visit", $date_of_expiry ); 
?>

Checking the cookie and do A or B

Then throughout the rest of the website (not present on the landing page) it will check if the cookie is present, and if present it does A, if not it does B, here's the code:

<?php 
    if(!isset($_COOKIE['adwords-customer']) || ($_COOKIE['adwords-customer'] != 'true')){
        echo "cookie set";
    } else {
        echo "cookie not set";
    }
?>

The Problem

The results are always "cookie set" and never else echo "cookie not set", thanks for any help in advance.


Solution

  • You see the ! here?

    if(!isset($_COOKIE['adwords-customer']) || ($_COOKIE['adwords-customer'] != 'true')){
       ^
        echo "cookie set";
    } else {
        echo "cookie not set";
    }
    

    It means that you're checking if it is NOT set, so that should be removed or invert the echos.

    And the != 'true' make sure you're not checking for boolean. If so, remove the quotes.


    Try giving this code a go!

    if(isset($_COOKIE['adwords-customer']) && ($_COOKIE['adwords-customer'] == true)){
        echo "cookie set";
    } else {
        echo "cookie not set";
    }
    

    If you find it now works but only on the URL that sets the cookie then ensure that your setcookie is set using / to indicate the entire domain, rather than just the /path/, e.g:

    $value = 'adwords-visit';
    
    setcookie("adwords-customer", $value);
    setcookie("adwords-customer", $value, time()+60);
    setcookie("adwords-customer", $value, time()+60, "/");