How can PHP be utilized to control access to images on a website based on the referring domain?
When serving images on a website, it may be necessary to restrict access based on the referring domain to prevent hotlinking or unauthorized use. This can be achieved using PHP by checking the HTTP Referer header and allowing access only to specified domains.
<?php
$allowed_domains = array('example.com', 'subdomain.example.com');
$referer = $_SERVER['HTTP_REFERER'];
if($referer) {
$referer_host = parse_url($referer, PHP_URL_HOST);
if(!in_array($referer_host, $allowed_domains)) {
header('HTTP/1.0 403 Forbidden');
exit;
}
} else {
header('HTTP/1.0 403 Forbidden');
exit;
}
// Serve image here
?>
Keywords
Related Questions
- What are the recommended best practices for handling form data in PHP when register_globals is disabled?
- How can the performance of LDAP authentication in PHP be optimized to minimize delays during the login process?
- What are the best practices for handling MySQL errors in PHP when executing SQL queries?