Block a List of IP Addresses in PHP

- 1 minute read

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(
    // 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!';
// If the process has not exited, then the IP address is not blacklisted.

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

    $blacklist = file('blacklist.txt', FILE_IGNORE_NEW_LINES);

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

Link to this section Adding a 403 response code

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

echo trim('
    <!DOCTYPE html><html><head><title>403</title></head><body>You are forbidden from accessing this resource!</body></html>

Link to this section 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!