File Download Counter with PHP & MySQL

Hello there! Today we are going to create a simple file download tracker with php and mysql.

To track downloads, we need to upload our file to uploads directory and add files metadata (like file name and path) to database table. When a user will try to download a file by file id the original file path will retrieve from database table then php will update download count value and file will be forced for download.

Live Demo Download Source

Step 1 - Creating MySQL Table

At first we need to create a mysql table called files. The table will hold three column with an auto increment field. The name file will hold file name, path will hold file path in server and count will hold the total number of downloads.

CREATE TABLE `files` (
  `name` varchar(64) NOT NULL,
  `path` varchar(30) NOT NULL,
  `count` int(10) DEFAULT '0',
  PRIMARY KEY (`id`)

Step 2 - File Upload

The upload.php file will allow us to upload file to server. It holds some basic file download handler functionality. When we will upload file it will move uploaded file to uploads directory as well as it will insert file metadata to mysql table. I have used a password verifier to prevent unauthorized acction.

include 'function.php';

$password = 'mypass'; // password
$max_upload_size = 1024*1024*2; // max file size

  if (!empty($_FILES['file']) and !empty($_POST['password']))
    // validate password
    if ($_POST['password'] === $password)
      // validate file size
      if ($_FILES['file']['size'] < $max_upload_size) {

        // generate upload path with unique file name
        $path = 'uploads/' . uniqid() . '.';
        $path .= pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
        $name = $_FILES['file']['name'];

        // move uploaded file to upload directory
        if ( move_uploaded_file($_FILES['file']['tmp_name'], $path) )
          // insert new file to mysql db
          mysql_query("INSERT INTO files (`name`, `path`)
                VALUES('$name', '$path')");

          // set success message
          $message = 'File Uploaded!';

        } else {
          $message = 'Upload fail';
      } else {
        $message = 'File is too large';
    } else {
      $message = 'Wrong Password!';
  } else {
    $message = 'File not set';

<!doctype html>
<html lang="en">
  <meta charset="UTF-8">
  <title>File download</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <div class="container">
    <h1>Upload File</h1>

    <?php if(isset($message)): ?>
      <p class="alert"><?php echo $message; ?></p>
    <?php endif ?>

    <!--file upload form-->
    <form action="" method="post" enctype="multipart/form-data">
      <input type="file" name="file">
      <input type="password" name="password" placeholder="Password">
      <input type="submit" name="upload" value="Upload">


Step 3 - File Download

The download.php file holds file download functionalities. This file retrieves file from database by it's id passed by file_id parameter. If it found file in database and file is exist in file system it updates counter value and forces file to download. We also need to off error reporting to avoid passing extra data and set php execution time to infinity to allow large file download by slow connection.

// off error reporting
// set unlimited php execution time

include 'function.php';
// connect to db

// read file id from url
$id = (int) isset($_GET['file_id']) ? $_GET['file_id'] : 0;
// retrieve file from db with id
$query = mysql_query("SELECT * FROM files WHERE id = '$id'");

if ($row = mysql_fetch_array($query))
  if (file_exists($row['path']))
    // increase counter value
    $count = ++$row['count'];
    // update count column
    mysql_query("UPDATE files SET count = '$count' WHERE id = {$row['id']} ");

    // set file download headers
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'. $row['name'] .'"');
    header('Content-Transfer-Encoding: binary');
    header('Connection: Keep-Alive');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($row['path']));

    // read file
  else {
    echo 'File not found!';
else {
  echo 'Bad Request!';



  1. hello very nice tutorial but I am getting some few errors,

    First: My files keep opening as damaged or corrupted
    Second: The path is being saved in the local folder instead of file name so I end up having funny letters and numbers in my directory.

    Where am I going wrong? please help.


    1. I don't know why it is happing! You got some bug on download.php file.

      First: Your file getting corrupted because this script suppling extra data. Set error_reporting(0);

      Second: getting funny file name it is due to bug on header('Content-Disposition: attachment; filename="'. $row['name'] .'"');

  2. Hello, Thank you for the info,

    But I have checked and I have included the error_reporting (0); but the error is still occurring.

    So how do i get rid of the funny names and number appearing in the directory, i would prefere the name of the file to be saved instead.

    Also i have just got another problem today, running the script in the local host works fine but when i run it on the live web, the script does not run.

    Please help.

  3. Thanks for your script. It is working well!

  4. i want to add my path media fire link it's counted

  5. i want to add my path media fire link it's counted

    Like that
    so it to be counted

  6. I am getting error like "bad request",files are successfully uploaded but in download process i can't get those files for download.How I rectify these bug? Please help me

  7. Than You So Much, I successfully done my work using your file uploading & downloading process code. now i don't showing uploading file in browser to order buy ASC or DESC. Please Help Me.

  8. Hi,
    my download.php is not opening, error ' bad request'
    would you know why please?

  9. Dapatkan disini , karena Obat Pelangsing slimming Capsule Di Apotik belum tersedia , karena slimming capsule tidak di jual di sembarang temapat termasuk di apotik pun tujuannya untuk menjaga ke aslian produk tersebut, karena sekarang banyak perusahaan yang meniru produk produk herbal sehingga herbal yang asli khasiatnya bisa di rusak oleh produk yang palsu. Untuk itu hati hati dengan slimming capsule

    and obat vig power capsule


Go to top