Hotlink protection is a mechanism that prevents other websites from directly using resources from your site, such as images, videos, files, etc., to avoid resource theft. In PHP, you can implement a simple hotlink protection mechanism by using the header() function when performing browser redirects.
When a resource from a website (such as an image, video, etc.) is directly linked by another website, it can lead to wasted bandwidth and resource misuse. To prevent this, you can check the Referer field in the HTTP header to determine the source of the request and decide whether to allow it.
header() is a function in PHP used to send raw HTTP headers. By checking the Referer field in the request, we can determine if the request is from a legitimate source website. If it is not legitimate, we can use the header() function to take appropriate action, such as redirecting to another page or denying access.
<?php
// Get the Referer field from the request
$referer = $_SERVER['HTTP_REFERER'];
<p>// Define the allowed source domain<br>
$allowed_domain = 'm66.net';</p>
<p>// Check if the Referer contains the allowed domain<br>
if (strpos($referer, $allowed_domain) === false) {<br>
// If the Referer is not legitimate, redirect to a denial page<br>
header('Location: <a rel="noopener" target="_new" class="" href="https://m66.net/403.html">https://m66.net/403.html</a>');<br>
exit;<br>
} else {<br>
// If the Referer is legitimate, allow access to the resource<br>
// Resource output can be done here<br>
echo "Welcome to my resource!";<br>
}<br>
?>
$_SERVER['HTTP_REFERER'] is used to retrieve the Referer field from the request, which typically contains the URL of the referring site.
The strpos() function checks if the Referer field contains the allowed domain (m66.net). If the domain is found, it indicates that the request is from a legitimate source.
If the Referer is not legitimate, the code redirects to a 403 error page using header('Location: https://m66.net/403.html'), indicating access is forbidden.
If the request is legitimate, access to the resource is granted, and a welcome message is displayed.
Referer may not always be included in every request, especially in browsers with strong privacy protection or when users have configured their browsers to block Referer headers. In such cases, the hotlink protection mechanism might not work perfectly.
This hotlink protection mechanism relies on the Referer field, so it is not 100% secure. To enhance security, other mechanisms such as signature verification or IP whitelisting can be implemented.
Related Tags:
header