GROVER.
GROVER.

Reputation: 4378

if statement continuing despite variable being false

I have been testing a simple long poll on my website, and for some reason a chunk of my server-side code is being executed despite the variable that triggers it ($init) being false.

I have a small hunch that the problem lies within the client-side code, but I can't seem to figure out what it is.

Code


Client Side - JavaScript:

window._Poll: {
    listen: function(init){
        $.ajax({
            url: "/poll.php",
            method: "post",
            data: { init: init },
            success: function(res){
                console.log(res);
                /* set the init variable to false in the next run */
                _Poll.listen(false);
            }
        });
    }, init: function(){
        /* set the init variable to true in the first run */
        this.listen(true);
    }
}
/* on page load */
_Poll.init();

Server Side - PHP:

set_time_limit(0);
session_write_close();

if(isset($_POST["init"]) && ($_POST["init"] == true || $_POST["init"] == false)){
    /* the first time this script is called, this variable is true - but for the
    *  second time and onwards it is false (like it should be) */
    $init = $_POST["init"];
    echo $init;

    /* therefore this block should only be firing once as init is only true once */
    if($init){
        if(/* some more database checking */){
            die("true");
        }
    } else {
        die("false");
    }
}

The console output for this the second time and onwards is

false true

When in reality it should be

false false


I have been really stuck on this, and from what I could find, nothing seems to be able to help me. So any help is appreciated,
Cheers.

Upvotes: 0

Views: 98

Answers (1)

Qirel
Qirel

Reputation: 26470

All values received from POST are strings. So if you're passing the string of "false", comparing that loosely to true will be a true result - "false" == true is true, as a string is truthy.

Checking for $_POST["init"] == true || $_POST["init"] == false doesn't make much sense, so you can instead check if the value is either equal to the strings "true" or "false"

if(isset($_POST["init"]) && (in_array(strtolower($_POST["init"])), ["true", "false"])){
    /* the first time this script is called, this variable is true - but for the
    *  second time and onwards it is false (like it should be) */
    $init = $_POST["init"];
    echo $init;

    /* therefore this block should only be firing once as init is only true once */
    if (strtolower($init) === "true"){
        if(/* some more database checking */){
            die("true");
        }
    } else { // Alternatively check if the string is "false", but then you can consider having a default return value other than "false"?
        die("false");
    }
}
``

Upvotes: 2

Related Questions