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!'; } ?>
Nice tutorial!
ReplyDeletehello very nice tutorial but I am getting some few errors,
ReplyDeleteFirst: 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
I don't know why it is happing! You got some bug on download.php file.
DeleteFirst: 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'] .'"');
Hello, Thank you for the info,
ReplyDeleteBut 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.
Thanks for your script. It is working well!
ReplyDeletei want to add my path media fire link ..so it's counted
ReplyDelete..Thanks
i want to add my path media fire link ..so it's counted
ReplyDelete..Thanks
Like that
http://uppit.com/4z37rhr5arx8/Avast_Internet_Sucurity-9.0.2008.177_Licence_File.rar
so it to be counted
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
ReplyDeleteThan 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.
ReplyDeleteHi,
ReplyDeletemy download.php is not opening, error ' bad request'
would you know why please?
thanks
dịch vụ thành lập doanh nghiệp công ty trọn gói
ReplyDeletedịch vụ thành lập doanh nghiệp công ty tại thanh xuân
dịch vụ thành lập doanh nghiệp công ty tại hà đông
dịch vụ thành lập doanh nghiệp công ty tại long biên
dịch vụ thành lập doanh nghiệp công ty tại cầu giấy
dịch vụ thành lập doanh nghiệp công ty tại hải phòng
dịch vụ thành lập doanh nghiệp công ty tại quận 3 tphcm
dịch vụ thành lập doanh nghiệp công ty tại quận đống đa
dịch vụ thành lập doanh nghiệp công ty tại quận thủ đức
dịch vụ thành lập doanh nghiệp công ty tại huyện đông anh
dịch vụ thành lập doanh nghiệp công ty tại huyện nhà bè
dịch vụ thành lập doanh nghiệp công ty tại huyện hoài đức
dịch vụ thành lập doanh nghiệp công ty tại bình dương
dịch vụ thành lập doanh nghiệp công ty tại hưng yên
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
ReplyDeleteand obat vig power capsule
I have read your blog its very attractive and impressive. I like it your blog.
ReplyDeletePHP Training in chennai | PHP Training Course
PHP Training in chennai | Online PHP Course
ReplyDeleteاعالى الخليج تقدم افضل خدمات نقل العفش الدولى المتميزه باسعار متميزة ومنها :
شركة شحن عفش من الرياض الى دبي
نقل عفش من الرياض الى الاردن شحن عفش من الرياض الى الاردن