Alex Rivera | Logout

PHP: how to check if the client is local?

Asked 2011-08-09T15:59:16.950
14

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?

Edit
Report

1 Answer

56

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
}
answered 2012-09-15T17:31:03.977

Your Answer