PHP download counter

A database will keep a list of all the downloads and each row in the database will also keep a count of the number of downloads for each item.

ob_start();
$id = (int)$_GET['id'];

We start by enabling output buffering to ensure that headers are not sent until the end of the code as we will redirect to user to the download once we have updated the counter.

$location = 'Location: download.php';
if($id > 0)

The initial location points to the list of files to download. If the id given is greater than zero then we read from the database the corresponding row.

mysql_connect('localhost','username','password');
mysql_select_db('db');
$output = mysql_fetch_assoc(mysql_query("SELECT downloads, link FROM download WHERE id='$id'"));

The only data we need from the database is the link to the download and the number of downloads. If the download link exists we will update the counter and redirect the user to the file to download.

if(file_exists($output['link']))
{
   $downloads = $output['downloads'] + 1;
   mysql_query("UPDATE download SET downloads = '$downloads' WHERE id = '$id'");
   $location = 'Location: '.$output['link'];
}

Now that we have done the update we need to redirect the user and clear the buffer.

header($location);
ob_end_clean();
exit();

Displaying the links

Finally we need to display the links to the user so that they can click the link to download the file.

$query1 = mysql_query('SELECT * FROM download');
while ($output = mysql_fetch_assoc($query1))

This simple query selects all the data from the table and the loop will allow us access to all the data. Below is the code that links to the download page.

echo ' <a href="downloadlink.php?id='.$output['id'].'">Download</a> - '.$output['downloads'].' downloads<br />';

Downloads

Categories

Tags

No tags

Social