Skip to content
PHP Logo

How can IP restrictions be implemented in PHP to control access to images?

To implement IP restrictions in PHP to control access to images, you can check the user's IP address against a list of allowed IP addresses before serving the image. If the user's IP address is not in the allowed list, you can deny access by returning a 403 Forbidden error.

php
$allowed_ips = array("192.168.1.1", "10.0.0.1"); // List of allowed IP addresses

$user_ip = $_SERVER['REMOTE_ADDR']; // Get the user's IP address

if (!in_array($user_ip, $allowed_ips)) {
    http_response_code(403); // Return a 403 Forbidden error
    exit("Access denied"); // Display a message to the user
}

// Serve the image to the user
header("Content-type: image/jpeg");
readfile("path/to/image.jpg");