Filter IP addresses with PHP

You may at some stage want to filter an online service based on IP address. In other words, you may want to block or grant access to a request based on their IP address. This can be handled in PHP by doing the following.

If you have the IP addresses, then it is trivial.


//First check IP address is valid
$request_ip = $_SERVER['REMOTE_ADDR'];

if ( !preg_match( "/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/", $request_ip ) )
    return false;

$blacklist = array(
'111.222.12.11',
'222.111.21.22',
'221.112.11.12'
);

//check that ip is not blacklisted
if ( in_array( $request_ip, $blacklist ) )
    return false;

If you want to include a range of IP addresses, best to use a regular expression.


$blacklist_ip_range = array(
    '/^122\.244\.(\d+)\.(\d+)/', //for IP address in the range 122.244.0.0 - 122.244.255.255
    '/^123\.(\d+)\.(\d+)\.(\d+)/', //for IP address in the range 123.0.0.0 - 123.255.255.255
);

foreach( $blacklist_ip_range as $ip ) {
    if( preg_match( $ip, $request_ip ) )
       	return false;
    }

If you have a better solution, then please let me know.

One thought on “Filter IP addresses with PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s