Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: how to check if the client is local?

Tags:

php

networking

ip

I need to check if a file is opened "locally" (same machine or network). I'm using:

<?php
if ((substr($_SERVER['REMOTE_ADDR'],0,8) == "192.168.") || ($_SERVER['REMOTE_ADDR'] == "127.0.0.1")) {
    // client is local
} else {
    // client is not local
}

But I'm not sure this is the best way.

What is a more foolproof way of doing this?

like image 214
user852091 Avatar asked Aug 09 '11 15:08

user852091


People also ask

How do I know if PHP is 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.

How do I find my localhost IP in PHP?

The simplest way to collect the visitor IP address in PHP is the REMOTE_ADDR. Pass the 'REMOTE_ADDR' in PHP $_SERVER variable. It will return the IP address of the visitor who is currently viewing the webpage.

What is $_ server [' Remote_addr ']?

$_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is viewing the current page. $_SERVER['REMOTE_HOST'] Returns the Host name from where the user is viewing the current page. $_SERVER['REMOTE_PORT']

What is a localhost server?

Localhost is the hostname or the computer that is currently in use to run a program, in which the computer has the role as a virtual server. In web development, you can develop a server by editing the code in the localhost and exporting your data to the server.


1 Answers

What Friek said is true, but provided that you know how to get the real client's IP, you can tell if it's a local address using PHP filters:

if ( ! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) )
{
    // is a local ip address
}
like image 84
Miguel Trias Avatar answered Sep 24 '22 00:09

Miguel Trias