Search code examples
phpimage.htaccessresolutionhotlinking

Preventing hotlinking by image resolution with .htaccess and PHP?


Preventing hotlinking altogether is easy, but can it be done based on the image resolution? I don't mind people hotlinking smaller images but I have a few +30 MiB ones that would make a bump in my bandwidth usage, so I would like to specifically prevent hotlinking of large images. I would like to this with PHP if possible since all my image are already displayed through a PHP script.


Solution

  • Hotlink detection is often based on checking the referer (sic!).

    You could easily add a filesize check in your delivering php script:

    if (filesize(FILENAME) > 30*1024*1024) {
        if ($_SERVER['HTTP_REFERER'] != '' && strpos($_SERVER['HTTP_REFERER'],'http://www.yourdomain.com/')===0) {
           header("Status: 500);
           echo "Hotlinking not allowed";
           exit(0);
        }
    }
    

    See PHP code for anti hotlinking, there are also some other examples which use Cookies (i.e., a php session to check if a user is authorized to view a picture).

    Hotlinking protection, however, always has some possible limitations: Not all clients are sending http referers (sic!), especially on https those are often missing, and not all clients are accepting cookies.