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.
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.
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();
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)
You might want to add some other
$_SERVER
keys there, likeX_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 shouldexplode()
them and loop through their values.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.