HomeForum › General Questions

How do I count the number of file downloads?

5 Replies 23 Views General Questions

Hello everyone,

I have a file download script but I want to track how many times each file has been downloaded. I have a MySQL database — how do I increment a counter each time a user downloads a file?

<?php
$file = "files/myfile.zip";
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=myfile.zip");
readfile($file);
?>

Thanks in advance!

Easy! Before serving the file, run an UPDATE query to increment the download count:

<?php
$file_id = (int) $_GET['id'];
$conn = mysql_connect("localhost", "user", "pass");
mysql_select_db("mydb");

// Increment download counter
mysql_query("UPDATE files SET downloads = downloads + 1
             WHERE id = $file_id");

$row = mysql_fetch_assoc(
    mysql_query("SELECT filename FROM files WHERE id = $file_id")
);
$file = "files/" . $row['filename'];
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=" . $row['filename']);
readfile($file);
?>

Make sure you have a downloads column (INT) in your files table.

Also always sanitize your inputs to prevent SQL injection! Casting to int like KSA did is the right approach. Recommended table structure:

CREATE TABLE files (
    id        INT AUTO_INCREMENT PRIMARY KEY,
    filename  VARCHAR(255),
    title     VARCHAR(255),
    downloads INT DEFAULT 0
);
← Back to Forum Login to Reply