Block IP Addresses from Your Site

A PHP snippet to block unwanted visitors by IP address

By al3arf 23 Nov 2003 1,842 views

This snippet allows you to block specific visitors from accessing your site by their IP address. Simply add the list of banned IPs and include the code at the top of any page you want to protect.

ip_block.php PHP
<?php
// List of banned IP addresses
$banned_ips = array(
    '192.168.1.100',
    '10.0.0.55',
    '172.16.0.200'
);

// Get current visitor's IP
$visitor_ip = $_SERVER['REMOTE_ADDR'];

// Check if the visitor's IP is banned
if (in_array($visitor_ip, $banned_ips)) {
    // Stop execution and show an error
    header('HTTP/1.0 403 Forbidden');
    die('<h1>403 - Access Denied</h1>');
}

// The rest of your page code continues normally here
?>
Usage Notes
  • Add this code at the top of every page you want to protect, or in a shared include file.
  • You can store the IP list in a database for easier management.
  • For permanent blocks, using .htaccess is more efficient than PHP.
← Back to Snippets