PHP download counter

04.Nov.2010

This is an example how PHP download counter could be made. This is just a basic but still functional example. So, in order to make a download counter we shall need three scripts:

  • download_file.php
  • download_count.php
  • show_download_number.php

First part of our PHP download counter script will be replacing actual file that should be downloaded, and will count number of times someone has downloaded that file. Lets say your HTML link to a file will not be file.xls, but download_file.php instead. This is what a whole file should look like:

1
2
3
4
5
6
7
8
9
$download_num = require 'download_count.php'; //get number of times file has been downloaded
$download_num++;
 
$my_stat = "download_count.php";
$handler = fopen($my_stat, 'w');
fwrite($handler, "<?php return " . $download_num . "; ?>"); //rewrite a whole download_count.php file
fclose($handler);
 
header('location: /file.xls'); //redirect user to his file

Second file (download_count.php) should be one line PHP file containing nothing but code from following snippet:

<?php return 0; ?>

This PHP file only returns value of download count, and since this is our setup, number of downloads should be zero.

Third file is used to see how many downloads has our counter recorded. So, include following snippet in your administration in order to present administrator with number of downloads of his file.

1
2
$download_num = require 'download_count.php';
echo 'PHP download counter has recorded: ' . $download_num . ' downloads of your file.xls';

Notice: This is a basic level script, and script of this kind should be able to track downloads of all files – and not just one. With simple adjustments this could be done, but it was not the scope of this article.