Hotlinking means using URLs from hosted website on another website, usually it is links to images or downloadable files but not only. There are a lot of methods how protect URL from hotlinking it. Websites hosted on Apache server may prevent hotlinking using appropriate configuration defined in .htaccess files. There are WordPress plugins to block hotlinking. Actually I do not have anything against hotlinking and what is presented below just my own exercise how prohibit offsite linking.
Most hotlinking protections are based on verification of Referer header in HTTP request. The Referer header is spelled with one “r” as presented on picture below:

The img tag to the image above looks as:
|
<img src="https://ladydebug.com/blog/codes/getimage.php?imagefile=../../../nohotlinking/httprequestheaders.png" alt="Hotlinking protection" /> |
If you copy image URL https://ladydebug.com/blog/codes/getimage.php?imagefile=../../../nohotlinking/httprequestheaders.png (the value of src attribute of the img tag) to browser address box you will see Good bye instead of image.
The same with curl:
|
# curl https://ladydebug.com/blog/codes/getimage.php?imagefile=../../../nohotlinking/httprequestheaders.png Good bye |
It is because the HTTP server ladydebug.com does not receive expected value of Referer header.
curl with appropriate referer header value gets the image file:
|
# curl –referer https://ladydebug.com https://ladydebug.com/blog/codes/getimage.php?imagefile=../../../nohotlinking/httprequestheaders.png -o httprequestheaders.png % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 32056 100 32056 0 0 123k 0 –:–:– –:–:– –:–:– 122k |
Finally getimage.php file which does this job of blocking hotlinks:
|
<?php if(isset($_GET["imagefile"])) { ""$referer_page = parse_url($_SERVER["HTTP_REFERER"], PHP_URL_HOST); if(strpos($referer_page, "ladydebug.com") === false) { echo "Good bye"; } else { $fileNameAndPath = $_GET["imagefile"]; $filename = basename($fileNameAndPath); $file_extension = strtolower(substr(strrchr($filename,"."),1)); switch( $file_extension ) { case "gif": $ctype="image/gif"; break; case "png": $ctype="image/png"; break; case "jpeg": case "jpg": $ctype="image/jpeg"; break; case "svg": $ctype="image/svg+xml"; break; default: $ctype="image/*"; } header("Content-Type:".$type); header("Content-Length: " .filesize($fileNameAndPath)); readfile($fileNameAndPath); } } else { echo "Error"; } ?> |