Skip to main content

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` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `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.

<?php
include 'function.php';
dbConnect();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
  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">
<head>
  <meta charset="UTF-8">
  <title>File download</title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
  <div class="container">
    <h1>Upload File</h1>

    <!--messages-->
    <?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">
    </form>

  </div>
</body>
</html>

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.

<?php
// off error reporting
error_reporting(0);
// set unlimited php execution time
set_time_limit(0);

include 'function.php';
// connect to db
dbConnect();

// 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
    readfile($row['path']);
  }
  else {
    echo 'File not found!';
  }
}
else {
  echo 'Bad Request!';
}

?>

Comments

  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.

    Thanks

    ReplyDelete
    Replies
    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'] .'"');

      Delete
  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.

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

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

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

    Like that

    http://uppit.com/4z37rhr5arx8/Avast_Internet_Sucurity-9.0.2008.177_Licence_File.rar
    so it to be counted

    ReplyDelete
  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

    ReplyDelete
  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.

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

    ReplyDelete
  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

    ReplyDelete
  10. These messages should be more often read by people.Penny

    ReplyDelete

Post a Comment

Popular posts from this blog

Multiple File Upload with PHP

Sometimes we need to allow our users to upload multiple file upload. On my previous post I was shown the basic of simple file upload with PHP. Today I am going to show you how to allow users to upload multiple files. It is almost similar like simple file upload but we need to do some modification with html markup and php code. multiple attribute is needed to add on the html markup. Major web browsers like Firefox, Chrome, Safari and IE 9+ support this attribute. Now I am going to show you how to upload multiple file with PHP and basic HTML form.

Live Comment System with jQuery Ajax PHP and MySQL

Recently I have been made a post that focused on how to submit form without page refreshing. That post shows the basic functionality of using jQuery Ajax. On the same follow this post will describe how we can create a comment system to post an instant comment without page refreshing. Let's start...

Resize Image While Uploading with PHP

On my previous post I was shown an example how to upload file with php and html. It was based on php simple image upload functionality. Today I am going to show you little bit advance of image uploading. Suppose if you run a website and want to allow users to upload image files than you need to think little bit about server's space and bandwidth. For this purpose you need to do some optimization with image files. Image resize while uploading is one of them. All major website do it in the same way. If a user uploads a 5mb image file they resize it in different sizes and store on there server. It helps them to seed up there website and reduce there budget. Now take a look, how we can do it ourself.