How can I detect if the user is on localhost in PHP?

Viewed 103264

In other words, how can I tell if the person using my web application is on the server it resides on? If I remember correctly, PHPMyAdmin does something like this for security reasons.

11 Answers

You can also use $_SERVER['REMOTE_ADDR'] for which IP address of the client requesting is given by the web server.

$whitelist = array(
    '127.0.0.1',
    '::1'
);

if(!in_array($_SERVER['REMOTE_ADDR'], $whitelist)){
    // not valid
}

I'm sorry but all these answers seem terrible to me. I would suggest rephrasing the question because in a sense all machines are "localhost".

The question should be; How do I run different code paths depending on which machine it is executed on.

In my opinion, the easiest way is to create a file called DEVMACHINE or whatever you want really and then simply check

file_exists('DEVMACHINE')

Remember to exclude this file when uploading to the live hosting environment!

This solution is not depending on network configuration, it can not be spoofed and makes it easy to switch between running "live-code" and "dev-code".

$_SERVER["REMOTE_ADDR"] should tell you the user's IP. It's spoofable, though.

Check this bounty question for a very detailed discussion.

I think what you remember with PHPMyAdmin is something different: Many MySQL Servers are configured so that they can only be accessed from localhost for security reasons.

Used this simple PHP condition

if($_SERVER['HTTP_HOST'] == 'localhost')
{
    die('Localhost');
}

Also there is another easy way to check is localhost or not: this code check if ip is in private or reserved range if it is thene we are in localhost.

  • support ipv4 & ipv6.
  • support ip range like 127.0.0.1 - 127.255.255.255

PHP Code:

function is_localhost() {

    $server_ip = null;

    if ( defined( 'INPUT_SERVER' ) && filter_has_var( INPUT_SERVER, 'REMOTE_ADDR' ) ) {
        $server_ip = filter_input( INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP );
    } elseif ( defined( 'INPUT_ENV' ) && filter_has_var( INPUT_ENV, 'REMOTE_ADDR' ) ) {
        $server_ip = filter_input( INPUT_ENV, 'REMOTE_ADDR', FILTER_VALIDATE_IP );
    } elseif ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
        $server_ip = filter_var( $_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP );
    }

    if ( empty( $server_ip ) ) {
        $server_ip = '127.0.0.1';
    }

    return empty( filter_var( $server_ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE | FILTER_FLAG_NO_PRIV_RANGE ));
}
  1. for get ip i use filter_input to avoid ip injection in code by user.
  2. in some case filter_input not supported in CGI scripts so if not exist i get ip in normal way with $_SERVER var.
  3. FILTER_VALIDATE_IP And FILTER_FLAG_NO_PRIV_RANGE are documented in php site you can find more information in this link.
Related