Wednesday, November 12, 2008

Scripting in an image with PHP

The title of this post may seem confusing to you. Let me make it clear. Here I am presenting a simple method for running a PHP script whenever a visitor of your sites retrieves a specific image file from your server.
In this example
Here, I am considering an image file hi.gif which when requested by a user runs PHP code to log the user's details. I assume, you're running Apache and PHP5. If you want a free host for this experiment then x10hosting is for you.

So, lets begin.
1. Open notepad and put the below code inside and save the file as "hi.gif"
$Date=date("F j, Y");
$Logging = $_SERVER['HTTP_USER_AGENT']." - ".$_SERVER['REMOTE_ADDR']." - ".$_SERVER['HTTP_REFERER']." - ".$Date;
$Post = fopen("$LogFile","a");
$icon = "../hi.gif";
header("Content-Type: image/jpeg");
$blah=fopen($icon, "rb");
$data=fread($blah, 512);
echo $data;

2. Now open notepad again and put this inside and save the file with name ".htaccess"
<FilesMatch "\.(bmp|gif)$">
SetHandler application/x-httpd-phpv2

3. Now login to your server's FTP daemon and in images directory put the hi.gif and .htaccessthat you created above. Also create a "log.txt" in your pc and upload this zero length file to the same directory. CHMOD log.txt to 777 or 666

4. Now go to one directory level up and upload the original real hi.gif that you want to show to the user.

5. Done!!! Yes! You're done. The URL to ur image script will be

The .htaccess file directs the server to parse all gif and bmp files in that folder as php scripts - the FilesMatch directive of Apache does that.
The hi.gif file accessed by the user is actually the PHP script that tracks user agent, referrer, ip and date of its accesser and then writes this info to log.txt and then returns to the user the contents of a real image hi.gif located one folder up. Thats it :)

There are many uses of this script including malicious ones. I leave it to yourself for thinking about its potential uses.

No comments: