What is the best way to restrict access to a PHP file from external domains?
To restrict access to a PHP file from external domains, you can check the HTTP referer header to ensure that the request is coming from an allowed domain. This helps prevent hotlinking and unauthorized access to your PHP files.
<?php
$allowed_domains = array('example.com', 'subdomain.example.com');
$referer = isset($_SERVER['HTTP_REFERER']) ? parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST) : '';
if (!in_array($referer, $allowed_domains)) {
header('HTTP/1.1 403 Forbidden');
exit('Access denied');
}
// Your PHP code here
?>
Keywords
Related Questions
- What are the potential pitfalls of using comma-separated values in SQL fields, especially when trying to query them with PHP?
- How can a PHP developer handle the conversion of time intervals with milliseconds from user input to accurate calculations using DateTime and DateInterval objects?
- What are the advantages of using cURL over file_get_contents for making HTTP requests in PHP?