Welcome folks today in this blog post we will be building a file upload and download management project in php and mysql database in browser. All the full source code of the application is shown below.
Get Started
In order to get started you need to download and install the xammp control panel
software which comes with the Apache web server and the phpmyadmin software as shown below. Now you need to start the server and the mysql database as shown below
Now you need to create the database
and tables inside the phpmyadmin
section as shown below
As you can see we have created the database which is filemanagement
and then we have created the table called files
which contain four columns which are the id
of the file which is the primary key and auto incremented and then we have the name of the file,size of the file and the no of times the file has been downloaded.
Directory Structure of the App
Now you can see the below files which constitute the file management app
Now you need to create the uploads
folder which will contain all the uploaded
files by the user. And then now we need to construct the index.php
which will be the homepage of the application.
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php include 'filesLogic.php';?> <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="style.css"> <title>Files Upload and Download</title> </head> <body> <div class="container"> <div class="row"> <form action="index.php" method="post" enctype="multipart/form-data" > <h3>Upload File</h3> <input type="file" name="myfile"> <br> <button type="submit" name="save">upload</button> </form> </div> </div> </body> </html> |
As you can see we are including the style.css
file for styling the app. It is mandatory just for styling I have added. After that we have a simple html5 form where the user will select the file to upload and then we have the button to submit the form as shown below. And we have also provided the action
attribute to the form. When the form submits we will redirect the user to the same index.php
file and the method is post
. And also we have added the encoding type attribute which is required when we upload media files.
Now you need to copy paste the below styles
inside the style.css
file as shown below
style.css
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
form { width: 30%; margin: 100px auto; padding: 30px; border: 1px solid #555; } input { width: 100%; border: 1px solid #f1e1e1; display: block; padding: 5px 10px; } button { border: none; padding: 10px; border-radius: 5px; } table { width: 60%; border-collapse: collapse; margin: 100px auto; } th, td { height: 50px; vertical-align: center; border: 1px solid black; } |
And now if you open the index.php
file inside the browser you will see the below output
As you can see in the above php code of index.php
we are including the filesLogic.php
file so now we need to create that file and copy paste the below code
filesLogic.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<?php // connect to the database $conn = mysqli_connect('localhost', 'root', '', 'filemanagement'); $sql = "SELECT * FROM files"; $result = mysqli_query($conn, $sql); $files = mysqli_fetch_all($result, MYSQLI_ASSOC); // Uploads files if (isset($_POST['save'])) { // if save button on the form is clicked // name of the uploaded file $filename = $_FILES['myfile']['name']; // destination of the file on the server $destination = 'uploads/' . $filename; // get the file extension $extension = pathinfo($filename, PATHINFO_EXTENSION); // the physical file on a temporary uploads directory on the server $file = $_FILES['myfile']['tmp_name']; $size = $_FILES['myfile']['size']; if (!in_array($extension, ['zip', 'pdf', 'docx','png','jpg'])) { echo "You file extension must be .zip, .pdf or .docx"; } elseif ($_FILES['myfile']['size'] > 1000000) { // file shouldn't be larger than 1Megabyte echo "File too large!"; } else { // move the uploaded (temporary) file to the specified destination if (move_uploaded_file($file, $destination)) { $sql = "INSERT INTO files (name, size, downloads) VALUES ('$filename', $size, 0)"; if (mysqli_query($conn, $sql)) { header('Location: downloads.php'); } } else { echo "Failed to upload file."; } } } |
As you can see we are connecting to the mysql
database using the username and password
and also we are providing the hostname which is localhost here and also the database name. After that we are fetching all the data from the mysql table files
using the mysqli_query()
method and then we are converting the result to an associative array. And after that we are checking if the submit button is pressed by the user inside the index.php
file. If it is pressed then we are simply uploading or moving the files to the uploads
folder. Before that we have the simple form validation also. Here we are only accepting the files which have the extensions .pdf,.zip.jpg and .png. You can specify the extensions inside the above array. You will get an error message as shown below if you upload wrong file
After that we are simply uploading the file using the move_uploaded_file()
function here we are providing the temp path and the permanent path as arguments. And after that we are inserting the file path into the mysql table and also we are inserting some other details such as the name,size of the file and also the number of downloads which is 0
when we first upload the file. And also we store the path as well inside the path column of the table. And after that we are redirecting the user to the downloads.php
page using the location header.
And now we will be writing the code inside the downloads.php
file where we will be showing the information of the mysql database inside the table structure as shown below
downloads.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?php include 'filesLogic.php';?> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="style.css"> <title>Download files</title> </head> <body> <table> <thead> <th>ID</th> <th>Filename</th> <th>size (in mb)</th> <th>Downloads</th> <th>Action</th> </thead> <tbody> <?php foreach ($files as $file): ?> <tr> <td><?php echo $file['ID']; ?></td> <td><?php echo $file['name']; ?></td> <td><?php echo floor($file['size'] / 1000) . ' KB'; ?></td> <td><?php echo $file['downloads']; ?></td> <td><a href="downloads.php?file_id=<?php echo $file['ID'] ?>">Download</a></td> </tr> <?php endforeach;?> </tbody> </table> </body> </html> |
As you can see we are once again including the filesLogic.php
php file at the very top and after that we are displaying the information of the uploaded file inside the table. And here basically we are running a foreach loop to loop through all the uploaded files which are present inside the database. And here we are printing the id
of the file. And then we are displaying the name,size and the no of times the file has been downloaded. And also we have the download button where the user can actually download the file when the button is clicked as shown below
And now we need to write the code so that when the user clicks the download button the file must download it as an attachment inside the browser. For this you need to edit the filesLogic.php
file and add the below code
filesLogic.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// Downloads files if (isset($_GET['file_id'])) { $id = $_GET['file_id']; // fetch file to download from database $sql = "SELECT * FROM files WHERE id=$id"; $result = mysqli_query($conn, $sql); $file = mysqli_fetch_assoc($result); $filepath = 'uploads/' . $file['name']; if (file_exists($filepath)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . basename($filepath)); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize('uploads/' . $file['name'])); readfile('uploads/' . $file['name']); // Now update downloads count $newCount = $file['downloads'] + 1; $updateQuery = "UPDATE files SET downloads=$newCount WHERE id=$id"; mysqli_query($conn, $updateQuery); exit; } } |
As you can see in the above code we are simply adding the required headers and downloading the file as an attachment when the download button is clicked by the user. And then we are also updating the files table where we are incrementing the value of the downloads column everytime by 1 when the file is downloaded by the user.