PHP code for anti hotlinking

If you can utilize the .htaccess method then great, additionally, as I said in my comment, a 100% fool proof way is to utilize base64 encoding. When you are displaying images, you can use this code to convert them to base64:

<?php
$imagedata = file_get_contents("/path/to/image.png");
$base64 = base64_encode($imagedata);
?>
<img src="data:image/jpeg;base64,<?= $base64; ?>" />

Also, if you want to get really creative, you can “RAT” the hotlink “thieves” out by displaying an alternative image using your .htaccess file… do this like so:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com/.*$ [NC]
RewriteRule \.(gif|jpg|png)$ http://www.mydomain.com/dontstealmystuff.png [R,L]

just make sure dontstealmystuff.png is available on the server

Leave a Comment