We learn more by looking for the answer to a question and not finding it than we do from learning the answer itself.

How to make a file download with counter?

A day back i just had a very interesting query from one of my friend who has asked me over “What if i want to download a file but also keep track of no of downloads” but with a special case that the download link should be hidden from the user. It means that download link shouldn’t be viewable to the user.

Like : <a href=”http://www.example.com/filename.doc”>Download Document</a>

It should be something hidden. In order to resolve this case, I came up with the following suggestions:

  • Instead of passing the direct filename pass the id of the file (give file a id) e.g 1234
  • Pass the File Id to a certain piece of code which keeps the track of download and pushes the file for download

Lets Start over to make this concept a reality:

<a href=”download/script.php?code=1234″>Download Document</a>

Now when a user click over the link a script is run which calls the script.php code and passes a code parameter with the id 1234.

Script File Code:

  • <?php
  • //Gets the file code $filecode = $_GET['code'];
  • //Write here the code to get the real name of the file from the database and update the counter for that file
  • //Let suppose the filename is 1234.doc
  • $file = ‘downloadfile/’.$filename;
  • //Rest of the code helps to push the file for download to the user
  • header(‘Content-type: application/force-download’);
  • header(‘Content-Transfer-Encoding: Binary’);
  • header(‘Content-disposition: attachment;
  • filename=”‘. basename($file) .’”‘);
  • header(‘Content-length: ‘. filesize($file) );
  • readfile( $file );
  • ?>

You can go ahead and try out the concept, if you have any certain query post a comment out for the help.

Leave a Comment

blog comments powered by Disqus