Brian
Brian

Reputation: 5

PHP check if the function returns boolean

So I got this function:

function hosting(){
    $localhostIP = array(
        '127.0.0.1',
        '::1'
    );
    if(!in_array($_SERVER['REMOTE_ADDR'], $localhostIP)){
        $localhost = false;
        return true;
    }else{
        $localhost = true;
        return $localhost;
    }
}

Later in the same file I want to call the function and check if the $localhost is true or false, this is what I got so far:

hosting();
if ($localhost == false) {
    echo"N";
}else{
   echo"Y";
}

It doesn't work and it is probably worst attempt ever, could someone show me how to check $localhost in the right way?

Thanks, Brian

Upvotes: 0

Views: 83

Answers (2)

Ugur
Ugur

Reputation: 1729

A better approach may be;

function isLocalhost($ipAddress) {
    $localhostIP = array(
        '127.0.0.1',
        '::1'
    );

    return in_array($ipAddress, $localhostIP);
}

//To check whether the request coming from localhost or not

if(isLocalhost($_SERVER['REMOTE_ADDR'])) {
   echo "Localhost";
} else {
   echo "Not Localhost";
}

Upvotes: 0

John Conde
John Conde

Reputation: 219794

You need to assign the return value from the function call to a variable:

$localhost = hosting();
if ($localhost == false) {
    echo"N";
}else{
   echo"Y";
}

Upvotes: 1

Related Questions