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.

Check for Valid XML with PHP

Simple function to check if XML is valid. It just loads the XML into DOMDocument and checks for errors.

/**
*  Takes XML string and returns a boolean result where valid XML returns true
*/
function is_valid_xml ( $xml ) {
    libxml_use_internal_errors( true );
    
    $doc = new DOMDocument('1.0', 'utf-8');
    
    $doc->loadXML( $xml );
    
    $errors = libxml_get_errors();
    
    return empty( $errors );
}