In web development, to ensure the security and integrity of your web applications is paramount. One effective measure to enhance the protection of your webpages is to control access based on IP addresses. PHP is a versatile server-side scripting language which allows developers to implement robust access control mechanisms.

In this article, we’ll explore how to block a specific IP address or a list of addresses from accessing a webpage using PHP. By leveraging PHP’s capabilities, you can fortify your web applications against unauthorized access and potential security threats. Let’s delve into the process of implementing IP-based access restrictions to bolster the security of your PHP-powered webpages.

Table of Contents

Block a List of IP Addresses Stored in a an Array

In PHP, you can block specified IP addresses from accessing a webpage by checking the visitor’s IP address against a predefined list and redirecting or denying access accordingly.

In this example:

  1. Replace "127.0.0.1", "192.168.1.1" with the IP addresses you want to block.
  2. The $_SERVER['REMOTE_ADDR'] variable is used to get the visitor’s IP address.
  3. The in_array function is used to check if the visitor’s IP is in the blocked list.
  4. If the IP is in the list, the script terminates with a denial message. You can customize this part to redirect the user or display a different message.

Block a List of IP Addresses Stored in a File

You can further modify this program to read the list of IP addresses from a file by using the file function to read the content of the file into an array. Here’s an example

Create a file named blocked_ips.txt with the following content:

127.0.0.1
192.168.1.1

In this modified version:

  1. The file blocked_ips.txt contains one IP address per line.
  2. The file function is used to read the content of the file into the $blockedIPs array.
  3. The rest of the script remains the same, checking if the visitor’s IP is in the blocked list and denying access accordingly.

Now, you can easily manage the list of blocked IP addresses by editing the blocked_ips.txt file without modifying the PHP script.

Block a List of IP Addresses Stored in a Database Table

Let’s further modify the code to retrieve the list of blocked IP addresses from a MySQL database, you’ll need to connect to the database and query the table. Here’s an example using MySQLi for database connectivity:

This script connects to the MySQL database, retrieves the list of blocked IP addresses from the blocked_ips table, and checks if the visitor’s IP is in the blocked list before allowing or denying access accordingly.