Serving an image as a script

Run a JPG image as a PHP script

A lot of times, we try to track user details by embedding an image in the email which is actually a script that does some logging before actually spitting out the image content. This is old-school.

logo.php :


$file = @fopen("details.csv", "a");
@fputcsv($file, [$IP, $B]);

$im = imagecreatefromjpeg('my-actual-logo.jpg'); 
header('Content-type: image/jpg');   

If you want to run an image file as a script before loading the actual image on the browser from the server, the suggested way of doing this is to get the .jpg extension run as PHP in .htaccess.

For example : AddHandler application/x-httpd-php .jpg

This is probably the most suggested way before, but registering all JPGs to run as PHP is not a great solution for just one or a few images. Also, AddHandler may not work in all setups. Another suggested method is to register just logo.jpg

mod_php :

<Files logo.jpg>
# mod_php
SetHandler application/x-httpd-php


<Files logo.jpg>
SetHandler php-cgi

Again, due to security reasons, the above could be disabled.

So, instead rewrite logo.jpg to run logo.php. This is bound to work on all server setups.

RewriteEngine On
RewriteRule ^logo.jpg$ logo.php

Did you find this article valuable?

Support Anjanesh Lekshminarayanan by becoming a sponsor. Any amount is appreciated!