How can PHP be used to redirect visitors to the homepage if they are accessing a protected file from an external source?
When a visitor tries to access a protected file on a website from an external source, it can pose a security risk. To prevent this, we can use PHP to check the HTTP referer header and redirect the visitor to the homepage if they are not accessing the file from an allowed source.
<?php
$allowed_domain = "example.com";
$referer = $_SERVER['HTTP_REFERER'];
if($referer && strpos($referer, $allowed_domain) === false) {
header("Location: /index.php");
exit();
}
?>
Keywords
Related Questions
- How can output buffering be used in PHP to prevent header modification issues when redirecting users to a new page after successful login?
- What are the best practices for storing timer data when using PHP for client-side functionality?
- What are the advantages of using a foreach loop compared to array_map for unit conversion in PHP?