How I Count Downloads

By Kidino @ 25 January, 2005

DIGG THIS DEL.ICIO.US COMMENTS EMAIL THIS

If you look at my download links, you can see that I am giving away ZIP files through a download link that has a .php ending instead of a .zip ending. Strange - but when you start to click on the link, you get the download dialog box.

Actually, by doing so, I am telling the PHP script to log each download request in a database, and at the same, the script will also deliver ZIP content to your browser. So later, I can count how many downloads I already get.

Anyway, here’s the script to do so.

< ?php
$host = 'database_host'; // normally just localhost
$username = 'database_username';
$password = 'database_password';
$database = 'database_name';

$conn = mysql_connect($host, $username, $password);
mysql_select_db($database);

$file = '../countdown.zip';
// physical location where you store the download
$fsize = filesize($file);
header ('Content-Type: application/x-zip-compressed');
// needs to be change with appropriate MIME Type
header ('Content-Disposition: inline; filename=countdown.zip');
// change to appropriate file name
header ('Content-Length: '. $fsize);

// do download here
$fp = fopen($file,'r') or die('fail to open file');
while (!feof($fp))
{
$data = fgetc($fp);
print($data);
}
fclose($fp);

$sql = 'insert into download_count (datetime, ip)'.
'values '.
"(now(), '$_SERVER[REMOTE_ADDR]')";
$dbr = mysql_query($sql) or die($sql);

exit();
?>

Of course, you will need a table in the database. You can use the following SQL script to create the table. You can just run the script through your phpMyAdmin access.

CREATE TABLE `download_count` (
`id` int(10) unsigned NOT NULL auto_increment,
`datetime` datetime default NULL,
`ip` varchar(15) default NULL,
PRIMARY KEY (`id`)
);

This is just a simple solution. For more downloads, you will need to create another table with a different name and a different script. Just rename the script and change the values of some variables in there.

Of course, you can expand this into a more complicated script. I am just giving you the simplest solution to the situation - counting download.

Oh yeah - forgot the mention. How to know how many downloads you have? You can check how many records you have in that table. That is easily determined with phpMyAdmin.

Just a note that the script also logs IP address and datetime of the download.

Have fun.

Sphinn
DIGG THIS DEL.ICIO.US COMMENTS EMAIL THIS
Comments TRACKBACK
  1. 1

    zulfadli said [28 October 2005 @ 2:44 pm]

    Simple & nice code.. I’ll try it for my website.. Thanks..

  2.  

     

    Leave a Reply

Kidino the Author

MoneyClicking Ezine
Your Free Doses of Tips & Tricks to Web Building for Internet Marketing. And Sometimes Marketing Strategies on the Net too ... all from yours truly, Iszuddin Ismail aka Kidino.

Name

Email





Read My XSitePro Review



Read My Affiliate Project X Review
Links
Categories

Internet Marketing And SEO Blog Top Sites