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?
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.
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.
$_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']
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With