How can PHP be used to prevent hotlinking and unauthorized access to images on a website?
Hotlinking and unauthorized access to images on a website can be prevented by checking the HTTP referer header of incoming requests. By verifying that the request is coming from the website itself and not from an external domain, you can restrict access to the images to only authorized users.
<?php
// Check if the request is coming from the same domain
$referer = $_SERVER['HTTP_REFERER'];
$allowed_domain = 'https://www.yourwebsite.com';
if($referer && strpos($referer, $allowed_domain) !== false) {
// Serve the image
$image_path = 'path/to/your/image.jpg';
header('Content-Type: image/jpeg');
readfile($image_path);
} else {
// Show an error image or message
$error_image = 'path/to/error/image.jpg';
header('Content-Type: image/jpeg');
readfile($error_image);
}
?>
Related questions
-
file_get_contents fopen PHP
-
strtotime date/time string timestamp
-
global variables security risks PHP