Hotlinking protection for Dummies and against Dummies

By | March 31, 2021

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:
Hotlinking protection
The img tag to the image above looks as:

<img src="" alt="Hotlinking protection" />

If you copy image URL (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
Good bye

It is because the HTTP server does not receive expected value of Referer header.

curl with appropriate referer header value gets the image file:

# curl –referer -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:

""$referer_page = parse_url($_SERVER["HTTP_REFERER"], PHP_URL_HOST);
      if(strpos($referer_page, "") === false)
         echo "Good bye";
         $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-Length: " .filesize($fileNameAndPath));
      echo "Error";

Leave a Reply

Your email address will not be published. Required fields are marked *