How to Check If User Is on Localhost in PHP?

In this article, we'll explore ways to check if we're on localhost or not.

Manually Setting a Flag to Determine Local and Production Environments

One particularly useful application of checking if we're on localhost or not is to determine and distinguish between development and production environments. If you, as a programmer, are in control of your environment, then you could simply set a flag globally, to determine the application environment. For example:

// manually defined environment flag
define('IS_PROD_ENV', true);

// is 'dev' environment?
if (! IS_PROD_ENV) {
    // do something...
}

For more flexibility, we could define an environment type variable, for example to distinguish between dev, staging and production environments. One way we could do this is like so:

// current environment type
define('ENV', 'dev');

// is 'staging' environment?
if (ENV === 'staging') {
    // do something...
}

Defining Environment Variables in Web Server Configuration:

Another way to add an environment variable would be by setting it in our web server virtualhost configuration. You could then access the environment variable in PHP using any one of the following:

  1. getenv()
  2. $_ENV superglobal array

Apache:

For example, in Apache we could do the following:

<VirtualHost *:80>
# virtual host info / settings
SetEnv ENV_TYPE "dev"
</VirtualHost>

Nginx:

Since nginx doesn't manage php processes like apache does, you will have to rely on what runs php on your server (such as php-fpm, php-cgi, etc.) and configure environment variables accordingly.

Docker:

In docker, this is quite straightforward; if you're using docker-compose.yml file for your configuration, under the PHP service container's configuration, you could simply add any environment variable under the environment key. For example:

version: '3'
services:

    php:
       environment:
         ENV_TYPE: 'dev'
         DEBUG: 'true'

Or, you could define an environment file like so:

version: '3'
services:

    php:
       env_file: ./.env

Consider for example, the .env file defined like the following:

ENV_TYPE=dev
DEBUG=false

This would allow us to retrieve ENV_TYPE and DEBUG variables using either getenv() or $_ENV superglobal in PHP. For example:

if ($_ENV['ENV_TYPE'] === 'dev') {
    // do something...
}

Determining Localhost Based on an Ip Address Whitelist

Most commonly, localhost uses the IP address 127.0.0.1 (which is an IPv4 "loopback address"). The IPv6 version of the same is ::1. Based on this information we can define an ip address whitelist to determine whether the web page was accessed from localhost or not, for example:

$whitelist = [
    // IPv4 address
    '127.0.0.1', 

    // IPv6 address
    '::1'
];

// code to check if ip exists in $whitelist

Depending on your networking system/setup, the localhost IP address might differ, in which case you can easily add that IP address to the whitelist.

Checking for Localhost Using the $_SERVER Superglobal Variable:

We could simply use the REMOTE_ADDR index on the $_SERVER superglobal array to retrieve the IP address of the requesting client from the web server. For example:

// are we on localhost?
if (in_array($_SERVER['REMOTE_ADDR'], $whitelist)) {
    // do something...
}

Although REMOTE_ADDR can be spoofed, it still represents the most reliable source of retrieving a client's IP address. You could dig deep to figure out the real IP address of a client, but for most use-cases this is enough and does the job well.

Validating IP Address With filter_var:

Using filter_var we could make sure we have a valid IP address as filter_var returns the filtered data on success, or false if the filter fails, for example:

$ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);

if ($ip !== false && in_array($ip, $whitelist)) {
    // do something...
}

Checking For Localhost Using filter_input:

An alternative to using the superglobal $_SERVER is to use INPUT_SERVER input type with the filter_input function to access and validate the REMOTE_ADDR variable. This has one of the following return values:

  • On Success: value of the requested variable is returned;
  • On Validation Fail: boolean false is returned;
  • On Variable Not Set: null is returned (e.g. if REMOTE_ADDR variable is not set).

For example:

$ip = filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP);

// are we on localhost?
if ($ip && in_array($ip, $whitelist)) {
    // do something...
}

On some implementations of FastCGI, using INPUT_ENV and INPUT_SERVER seem to have strange side-effects as either one (or even both) may return null values unexpectedly. So, use with caution when using FastCGI.

Workaround for Using INPUT_SERVER With FastCGI:

To be on the safe side, you could simply use the superglobal $_SERVER variable instead. Or, alternatively, you could check if the variable (e.g. REMOTE_ADDR) exists on:

  1. INPUT_SERVER;
  2. INPUT_ENV;
  3. $_SERVER superglobal;
  4. And if all fails, return null finally.

For example:

if (filter_has_var(INPUT_SERVER, 'REMOTE_ADDR')) {
    $ip = filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP);
} else if (filter_has_var(INPUT_ENV, 'REMOTE_ADDR')) {
    $ip = filter_input(INPUT_ENV, 'REMOTE_ADDR', FILTER_VALIDATE_IP);
} else if (isset($_SERVER['REMOTE_ADDR'])) {
    $ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
} else {
    $ip = null;
}

// check if we're on localhost
if ($ip && in_array($ip, $whitelist)) {
    // do something...
}

This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.