Skip to content
Advertisement

PHP Warning: file_get_contents(http://ipecho.net/plain): failed to open stream: Connection timed out in

I have an error here and I don’t know where the problem is exactly. I am trying to make a PHP file and deny anyone to use the script except the IP that I have entered into the code:

$pass = '192.168.x.x'; //here is the ip of the client
if (file_get_contents('http://ipecho.net/plain') !== $pass) {

When I use the code Ii have problem

PHP Warning:  file_get_contents(http://ipecho.net/plain): failed to open stream: Connection timed out

Advertisement

Answer

Why you use that site for getting the client’s IP?

You can use this PHP function for getting the client’s IP address.

whenever the application is behind a proxy(e.g, Cloudflare):

function get_client_ip() {
    $ipaddress = '';
    if ($_SERVER['HTTP_CLIENT_IP'])
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if($_SERVER['HTTP_X_FORWARDED_FOR'])
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if($_SERVER['HTTP_X_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if($_SERVER['HTTP_FORWARDED_FOR'])
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if($_SERVER['HTTP_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if($_SERVER['REMOTE_ADDR'])
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

and when the application isn’t behind a proxy:

function get_client_ip() {
    return $_SERVER['REMOTE_ADDR'];
}

Final code should be like this:

$pass = '192.168.x.x'; //here is the ip of the client
if (strcmp(get_client_ip(),$pass) == 0 ) {
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement