IN WordPress and Drupal both, there are built-in methods to add specific IP addresses or other means of identification to block them. If you’re looking for code to do the same, here are the snippets.
In Drupal, you can use “settings.php” file and in WordPress, you can use “wp-config.php” file to add these snippets.
PHP code snippets to block IP addresses
There are few advantages to use PHP code to block the IP addresses.
- First of all, you don’t need to install the plugin that will add data to database and then fetch it every time.
- You won’t need the additional code of plugin.
- A plugin requires making connections to database and also it requires the WordPress or Drupal to be loaded.
- If you site is already affected by DDoS attack then you can’t add a plugin/module.
Add this code to block a single IP address
if ($_SERVER['REMOTE_ADDR'] == '192.168.1.1') {
header('HTTP/1.0 403 Forbidden');
exit;
}
👉 Do not forget to replace the IP address (192.168.1.1) with the one you want to block.
Add this code to block a range of IP addresses
// IPv4: Single IPs and CIDR.
$request_ip_blocklist = [
'192.0.2.38',
'192.0.3.125',
'192.0.67.0/30',
'192.0.78.0/24',
];
$request_remote_addr = $_SERVER['REMOTE_ADDR'];
// Check if this IP is in blocklist.
if (!$request_ip_forbidden = in_array($request_remote_addr, $request_ip_blocklist)) {
// Check if this IP is in CIDR block list.
foreach ($request_ip_blocklist as $_cidr) {
if (strpos($_cidr, '/') !== FALSE) {
$_ip = ip2long($request_remote_addr);
list ($_net, $_mask) = explode('/', $_cidr, 2);
$_ip_net = ip2long($_net);
$_ip_mask = ~((1 << (32 - $_mask)) - 1);
if ($request_ip_forbidden = ($_ip & $_ip_mask) == ($_ip_net & $_ip_mask)) {
break;
}
}
}
}
if ($request_ip_forbidden) {
header('HTTP/1.0 403 Forbidden');
exit;
}
👉 Do not forget to replace the IP addresses with the ones you want to block.
PHP code snippets to block User Agents
You can also target unwanted user agents and block them from visiting your site either by “robots.txt” file or with PHP stripos function. I’ll show you the second method here.
The stripos function from PHP is a case-insensitive match and it’s really helpful while blocking the bots or crawlers like as Curl/dev vs curlBot.
Add this code to block a single bot
if (stripos($_SERVER['HTTP_USER_AGENT'], 'UglyBot') !== FALSE) {
header('HTTP/1.0 403 Forbidden');
}
👉 Do not forget to replace the UglyBot with the one you want to block.
Add this code to block a list of bots
$bots = ['UglyBot', 'PetalBot'];
foreach ($bots as $bot) {
if (stripos($_SERVER['HTTP_USER_AGENT'], $bot) !== FALSE) {
header('HTTP/1.0 403 Forbidden');
exit;
}
}
👉 Do not forget to replace the $bots array values with the ones you want to block.
Credit: Pantheon
block examples IP Address User Agent