Block IP Addresses in Joomla
A single visitor is hammering your contact form, scraping your catalogue, or leaving spam faster than you can moderate it, and every request comes from the same address. You want that address gone today, not after you install and configure a full security suite, and you may not have access to .htaccess on managed hosting. Blocking an IP address in Joomla can be handled with a few lines of code instead. You can do it with Code Snippets using a simple PHP snippet.
The PHP Snippet Code
Set Code Type to PHP, then use this snippet. It reads the visitor's IP address on every frontend page load and compares it to your block list before the page is rendered. Matching is done from the start of the address, so a full address like 203.0.113.10 blocks one visitor, while a prefix like 198.51.100. blocks that entire range. Blocked visitors get a 403 Forbidden response and a short message instead of your site.
use Joomla\CMS\Factory;
// IP addresses or prefixes to block.
$blockedIPs = [
'203.0.113.10',
'198.51.100.',
];
// Message shown to blocked visitors.
$message = 'Access denied.';
// Do not edit below.
$app = Factory::getApplication();
$ip = (string) $app->getInput()->server->getString('REMOTE_ADDR', '');
if ($ip !== '')
{
foreach ($blockedIPs as $blockedIP)
{
$blockedIP = trim($blockedIP);
if ($blockedIP === '' || strpos($ip, $blockedIP) !== 0)
{
continue;
}
$app->setHeader('Status', '403 Forbidden', true);
$app->sendHeaders();
echo $message;
$app->close();
}
}
Tip: If your site sits behind Cloudflare or another reverse proxy, REMOTE_ADDR holds the proxy's address, not the visitor's. In that case read HTTP_CF_CONNECTING_IP (Cloudflare) or the first address in HTTP_X_FORWARDED_FOR instead, and only trust those headers when you know the proxy sets them.
Double-check your list before publishing. Locking out your own address means you have to disable the snippet from another network or unpublish it directly in the database.
How to add this snippet
- Install Code Snippets if it is not installed already.
- Go to your Joomla Administrator area.
- Open Components → Code Snippets.
- Click New.
- Select PHP as the snippet type.
- Paste the code to block IP addresses above and replace the sample addresses with your own.
- Select Insertion Method → Page Load.
- Publish the snippet.
- Optionally, open the Conditional Logic tab to restrict which pages or users the snippet runs on. Leave it empty to run it site-wide. Learn more in Using Conditional Logic.
PHP snippets run on the frontend of your site, so this protects your public pages. Your Joomla Administrator area is not affected.
Congrats! You've just added IP blocking functionality to Joomla without installing another plugin or adding unnecessary bloat to your site.
For instance, to learn more about how the PHP Snippet works, visit our documentation: https://www.tassos.gr/docs/tassos-code-snippets/types/php