(Snippet) Blocking IPs from a list file with PHP

I came across these functions this evening after brushing off the old forum code. Someone sent me an email asking about this too so I’ll post it here.

This shows how to read the contents of a blocklist file (where each entry is on a seperate line) into an array and scan it for a given IP :

blocklist.txt

91.121.24.139
200.49.176.139

Note : You can include partials like 91.121.24. as well.

And the blocklist and IP check functions

/**
* Blocklist function checks a user IP against an array of blocked IPs.
* I'd avoid using a hard coded filename/path in this so 
* consider this as just a demo.
* 
* @param string $ip The IP address to check
* @return bool true If IP is in blocklist. Defaults to false.
*/
function blocklist($ip) {
	$blocked = false;
	$ipList = file('blocklist.txt', FILE_SKIP_EMPTY_LINES)
		or exit("Unable to open blocklist file");

	foreach ($ipList as $entry) {
		if(strstr($ip, $entry, true)) {
			$blocked = true;
			break;  // No need to loop further
		}
	}
	return $blocked;
}


/**
* Gets the IP address of the current user.
* Note, this function also tries to get the forwarded IP from a 
* proxy if the user is behind one.
*
* @return string $ip The user IP or forwarded IP from proxy
*/
function getUserIP() {
	$_p = $_SERVER["HTTP_CLIENT_IP"];

	if(empty($_p)) {
		$_p = $_SERVER["HTTP_X_FORWARDED_FOR"];
	
		if(!empty($_p)) {
			$_p = explode(',', $_p);
			$_p = [sizeof($_p) - 1];
		}
		else {
			$_p = $_SERVER["REMOTE_ADDR"];
		}
	}
	return trim($ip);
}

How to use

In your header include files or on top of your other scripts, add the following

$userIP = getUserIP();
// If the IP is in the blocklist, send a 403 Forbidden header
if(blocklist($userIP)) {
	header("HTTP/1.1 403 Forbidden");
	exit(); // We're done here
}

Note: these are added on top because… well… why waste resources pulling up the rest of the script and executing code if you’re not going to serve content to the blocked user?

edit_
Made some changes to the IP detection script. It now checks for HTTP_CLIENT_IP first.

Advertisements

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