Watermark on Hot Linking

I tried to find some script that allowed me to watermark photos that where being hot linked, and just those.
Didn’t find any script that did just what I wanted but found parts of it and then I rewrote and added caching for it.

This script is named /hl/watermark.php there of the “../” in the paths.
The directory “cache” needs to be writeable by the webserver.

You can use most of the available TTF-fonts you just need to upload it to same directory. /hl that is.

The PHP Code:

$font = "./kberry.ttf";

$impath = str_replace("../","", $_GET["image"]);

$cachefile = "./cache/".md5($impath) . ".png";
if (file_exists("../".$impath)) {
$file_md5 = $cachefile.".md5";
$md5_new_file = trim(md5_file("../" . $impath));
$md5_old_file = trim(@file_get_contents($file_md5));
@rename($file_md5, $file_md5.".bak");
$fp = fopen($file_md5, 'w');
fwrite($fp, $md5_new_file);
fclose($fp);

@rename($cachefile.".path", $cachefile.".path.bak");
$fpath = fopen($cachefile.".path", 'w');
fwrite($fpath, "/".$impath);
fclose($fpath);

if(($md5_new_file <> $md5_old_file) || !file_exists($cachefile))
{
$ext = end ( explode ( ".", $impath ) );

switch ( $ext ) {
case "jpg":
$image = imagecreatefromjpeg ( "../" . $impath ); break;
case "jpeg":
$image = imagecreatefromjpeg ( "../" . $impath ); break;
case "png":
$image = imagecreatefrompng ( "../" . $impath ); break;
case "gif":
$image = imagecreatefromgif ( "../" . $impath ); break;
}
$text = "(c) clearshots.se";
$font_size = 28;

$size = imagettfbbox ( $font_size, 0, $font, $text );
$text_width = $size[2] + $size[0] + 8;
$text_height = $size[1] + $size[7];

$image_width = imagesx ( $image );
$image_height = imagesy ( $image );

$text_x = $image_width - $text_width - 5;
$text_y = $image_height - $text_height - 40;

$shadow_x = $text_x + 2;
$shadow_y = $text_y + 2;

imagettftext ( $image, $font_size, 0, $shadow_x, $shadow_y, imagecolorallocate ( $image, 0, 0, 0 ), $font, $text );
imagettftext ( $image, $font_size, 0, $text_x, $text_y, imagecolorallocate ( $image, 255, 195, 60 ), $font, $text );

 

 

header ( “Content-Type: image/png” );

@unlink($cachefile);
imagepng ( $image );
imagepng( $image, $cachefile,0);
imagedestroy ( $image );
}
else
{
@unlink($cachefile.".md5.bak");
@unlink($cachefile.".path.bak");
header ( "Content-Type: image/png" );
readfile($cachefile);
}
} else {
header ( "Content-Type: image/png" );
readfile("./404.png");
}
? >

The .htacess file

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?clearshots.se/.*$ [NC]
RewriteRule (.*.(png|gif|jpeg|jpg)) http://www.clearshots.se/hl/watermark.php?image=$1 [R,L]

 

Leave a Reply

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