mullac. codes

December 22, 2007

Transparent file logger for Apache.

Filed under: CallumJ — Tags: , , , , , , , — callumj @ 1:56 am

I have written a small PHP file that will log all downloads for a specific directory with the help of Apache’s ModRewrite. This is so you can place the file in the middle and have it log all downloads without having to modify a specific CMS’s settings to handle the new PHP file. To the user it appears as if the file is actually being served normally.

PHP

include ("/var/www/html/flv_script/mysql.php");
//a transparant file download script
//logs to SQL
//Written by Callum Jones (mullac.wordpress.com)
$uri = mysql_real_escape_string($_GET['uri']);
$filename = "/var/www/html/downloads/". $uri;
$handle = fopen($filename, "r");
$contents = fread($handle, filesize ($filename));
if (!empty($contents) && (filesize ($filename) != 0)) {
header('Content-Type: application/octet-stream');
echo $contents;
mysql_query("INSERT INTO `gen`.`fileadmin_log` (
`referrer`,
`id` ,
`uri` ,
`time` ,
`IP`
)
VALUES ('". $_SERVER['HTTP_REFERER'] ."', '', '". $uri ."', CURRENT_TIMESTAMP , '". $_SERVER['REMOTE_ADDR'] ."');");
} else {
echo "No file available";
echo "";
}fclose($handle);

.htaccess

RewriteEngine On
RewriteBase /
RewriteRule ^downloads/(.+) file.php?uri=$1

SQL table

CREATE TABLE IF NOT EXISTS `fileadmin_log` (
`id` bigint(10) NOT NULL auto_increment,
`uri` varchar(255) NOT NULL,
`time` timestamp NOT NULL default CURRENT_TIMESTAMP,
`IP` varchar(255) NOT NULL,
`referrer` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Feel free to email me (callum.jones at gmail com) if you want to know more.

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.