DEV Community

Nathan
Nathan

Posted on • Originally published at natclark.com

Block a List of IP Addresses in PHP

Here's a simple PHP snippet that you can place at the top of a file to determine whether the IPv4 address of a request is blacklisted:

$blacklist = array(
    '127.0.0.1',
    '192.168.1.1',
    // etc.
);

$ip = isset($_SERVER['REMOTE_ADDR']) ? trim($_SERVER['REMOTE_ADDR']) : '';

if (($key = array_search($ip, $blacklist)) !== false) {
    echo 'You are forbidden from accessing this resource!';
    exit();
}

// If the process has not exited, then the IP address is not blacklisted.
Enter fullscreen mode Exit fullscreen mode

You could also pull a list of IP addresses from a file:

    $blacklist = file('blacklist.txt', FILE_IGNORE_NEW_LINES);
Enter fullscreen mode Exit fullscreen mode

In the above example, each line of blacklist.txt should contain a single and unique IP address.

Adding a 403 response code

If you haven't already, you might want to consider responding with a 403 error:

http_response_code(403);
echo trim('
    <!DOCTYPE html><html><head><title>403</title></head><body>You are forbidden from accessing this resource!</body></html>
');
exit();
Enter fullscreen mode Exit fullscreen mode

Conclusion

Anyway, this is just one of many simple ways to block a list of IP addresses from accessing a resource on your PHP server.

If you're running into issues, remember to add this snippet to the top of the files you want to add it to!

Top comments (2)

Collapse
 
moopet profile image
Ben Sinclair • Edited

You might want to add some other $_SERVER keys there, like X_FORWARDED_FOR off the top of my head, depending on whether things are going through proxies, etc.

Also, just remembered, these values can be comma-separated lists (depending on hosting), like "123.123.123.123,101.101.101.101" so you should explode() them and loop through their values.

Collapse
 
natclark profile image
Nathan

All good points - this is a more primitive solution as it stands, and I should probably at least mention how you can start implementing things like proxy detection.