0

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

1
  • did you try $localhost = hosting() Commented Mar 15, 2015 at 23:38

2 Answers 2

1

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

$localhost = hosting();
if ($localhost == false) {
    echo"N";
}else{
   echo"Y";
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, works fine now. Just one more question how can I check if the function is true or false if its written like this:function hosting(){ $localhostIP = array( '127.0.0.1', '::1' ); if(!in_array($_SERVER['REMOTE_ADDR'], $localhostIP)){ return true; }else{ return false; } }
Your question does not make any sense. Your code exactly what you're aksing.
Sorry, here: sandbox.onlinephpfunctions.com/code/… this time there is no $localhost, just {return true;}. How can I check that? Edit: Link works fine now
0

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";
}

1 Comment

Thanks for sharing, looks like much better solution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.