Skip to main content

Upload and Download Files in PHP/PDO Tutorial

Language

In this simple source code, you can learn how to manage (upload/download) files using PHP/PDO. The simple project can store different types/formats of files and also the user can download the uploaded file. The source code can detect if the file name has duplicates and will automatically add a number for example if the filename "sample.pdf" already exists in the database the system will store the file as "sample_2.pdf" and if ever user will upload a file using the same filename the system will also check if the new filename has no duplicates. In addition to the example scenario, if the user will upload "sample.php", the system will change it into "sample_3".

Acceptable File Format extensions

  • pdf
  • txt
  • html
  • htm
  • exe
  • zip
  • doc
  • xls
  • ppt
  • gif
  • png
  • jpeg
  • jpg
  • php

Creatin a Simple Upload/Download System

Set up a local webserver

File Upload Form

  1. <form enctype="multipart/form-data" action="" name="form" method="post">
  2. Select File
  3. <input type="file" name="file" id="file" /></td>
  4. <input type="submit" name="submit" id="submit" value="Submit" />
  5. </form>

File Upload PHP Script

  1. <?php
  2. $conn=new PDO('mysql:host=localhost; dbname=demo', 'root', '') or die(mysql_error());
  3. if(isset($_POST['submit'])!=""){
  4. $name=$_FILES['file']['name'];
  5. $size=$_FILES['file']['size'];
  6. $type=$_FILES['file']['type'];
  7. $temp=$_FILES['file']['tmp_name'];
  8. $fname = date("YmdHis").'_'.$name;
  9. $chk = $conn->query("SELECT * FROM upload where name = '$name' ")->rowCount();
  10. if($chk){
  11. $i = 1;
  12. $c = 0;
  13. while($c == 0){
  14. $i++;
  15. $reversedParts = explode('.', strrev($name), 2);
  16. $tname = (strrev($reversedParts[1]))."_".($i).'.'.(strrev($reversedParts[0]));
  17. $chk2 = $conn->query("SELECT * FROM upload where name = '$tname' ")->rowCount();
  18. if($chk2 == 0){
  19. $c = 1;
  20. $name = $tname;
  21. }
  22. }
  23. }
  24. $move = move_uploaded_file($temp,"upload/".$fname);
  25. if($move){
  26. $query=$conn->query("insert into upload(name,fname)values('$name','$fname')");
  27. if($query){
  28. header("location:index.php");
  29. }
  30. else{
  31. }
  32. }
  33. }
  34. ?>

Uploaded file Table List

  1. <table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="example">
  2. <thead>
  3. <tr>
  4. <th width="90%" align="center">Files</th>
  5. <th align="center">Action</th>
  6. </tr>
  7. </thead>
  8. <?php
  9. $query=$conn->query("select * from upload order by id desc");
  10. while($row=$query->fetch()){
  11. $name=$row['name'];
  12. ?>
  13. <tr>
  14. <td>
  15. &nbsp;<?php echo $name ;?>
  16. </td>
  17. <td>
  18. <button class="alert-success"><a href="download.php?filename=<?php echo $name;?>&f=<?php echo $row['fname'] ?>">Download</a></button>
  19. </td>
  20. </tr>
  21. <?php }?>
  22. </table>
  23.  

Download File Script

  1. <?php
  2. function output_file($file, $name, $mime_type='')
  3. {
  4. if(!is_readable($file)) die('File not found!');
  5.  
  6. $size = filesize($file);
  7. $name = rawurldecode($name);
  8. $known_mime_types=array(
  9. "pdf" => "application/pdf",
  10. "txt" => "text/plain",
  11. "html" => "text/html",
  12. "htm" => "text/html",
  13. "exe" => "application/octet-stream",
  14. "zip" => "application/zip",
  15. "doc" => "application/msword",
  16. "xls" => "application/vnd.ms-excel",
  17. "ppt" => "application/vnd.ms-powerpoint",
  18. "gif" => "image/gif",
  19. "png" => "image/png",
  20. "jpeg"=> "image/jpg",
  21. "jpg" => "image/jpg",
  22. "php" => "text/plain"
  23. );
  24. if($mime_type==''){
  25. $file_extension = strtolower(substr(strrchr($file,"."),1));
  26. if(array_key_exists($file_extension, $known_mime_types)){
  27. $mime_type=$known_mime_types[$file_extension];
  28. } else {
  29. $mime_type="application/force-download";
  30. };
  31. };
  32.  
  33.  
  34.  
  35. if(ini_get('zlib.output_compression'))
  36. ini_set('zlib.output_compression', 'Off');
  37. header('Content-Type: ' . $mime_type);
  38. header('Content-Disposition: attachment; filename="'.$name.'"');
  39. header("Content-Transfer-Encoding: binary");
  40. header('Accept-Ranges: bytes');
  41. header("Cache-control: private");
  42. header('Pragma: private');
  43. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  44. if(isset($_SERVER['HTTP_RANGE']))
  45. {
  46. list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
  47. list($range) = explode(",",$range,2);
  48. list($range, $range_end) = explode("-", $range);
  49. $range=intval($range);
  50. if(!$range_end) {
  51. $range_end=$size-1;
  52. } else {
  53. $range_end=intval($range_end);
  54. }
  55. $new_length = $range_end-$range+1;
  56. header("HTTP/1.1 206 Partial Content");
  57. header("Content-Length: $new_length");
  58. header("Content-Range: bytes $range-$range_end/$size");
  59. } else {
  60. $new_length=$size;
  61. header("Content-Length: ".$size);
  62. }
  63. $chunksize = 1*(1024*1024);
  64. $bytes_send = 0;
  65. if ($file = fopen($file, 'r'))
  66. {
  67. if(isset($_SERVER['HTTP_RANGE']))
  68. fseek($file, $range);
  69.  
  70. while(!feof($file) &&
  71. ($bytes_send<$new_length)
  72. )
  73. {
  74. $buffer = fread($file, $chunksize);
  75. print($buffer);
  76. flush();
  77. $bytes_send += strlen($buffer);
  78. }
  79. fclose($file);
  80. } else
  81.  
  82. die('Error - cannot open file.');
  83. die();
  84. }
  85. $file_path='upload/'.$_REQUEST['f'];
  86. output_file($file_path, ''.$_REQUEST['filename'].'', 'text/plain');
  87. ?>

That source code above are important script you will need in developing a simple Upload and Download File System. You can also use bootstrap for the design of your project. Feel Free to Copy and paste the source codes above and try develop a simple file upload and download system on your own. Also, you can download the working project source code below.

DEMO

Happy Coding :)

For more PHP tutorials, visit the link below.

PHP Tutorials

For a Free PHP project w/ Source Code, visit the link below.

Free PHP Project with Source Code

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Comments

Submitted byanony (not verified)on Fri, 07/21/2017 - 17:06

download function, there is no file downloaded. System prompt file not exist.
Submitted bynikosttttttt (not verified)on Thu, 02/15/2018 - 23:44

thank you very much
Submitted bykartik124 (not verified)on Sat, 03/24/2018 - 21:43

In reply to by nikosttttttt (not verified)

what changes you made in the download file
Submitted byPriyaSinha (not verified)on Wed, 04/04/2018 - 02:51

Thanks alot. It's woking fine.
Submitted byrookie (not verified)on Wed, 05/09/2018 - 03:05

Thank you so much for the code. You are the best!
Submitted byglen09090990 (not verified)on Wed, 05/23/2018 - 10:33

Hi, download button is not working, Please check. Thank you
Submitted byManish Pareek (not verified)on Thu, 06/20/2019 - 20:15

Just Change Line No 9 to move_uploaded_file($temp,"upload/".$name);
Submitted byMirek (not verified)on Wed, 02/17/2021 - 16:37

Thanks for tutorial ! Tell me.. how do : I want copy download link and share it - how display only http link ?
Submitted byparth kakadiya (not verified)on Sat, 04/03/2021 - 19:55

The requested URL was not found on this server.

Add new comment