How do I download a file using PHP and Mysql DB

I am new to this and I am really stuck on how to download a file I have managed to upload on my local server.

My uploaded script is –

require_once ('dbcon.php');

if(isset($_POST['log'])){
foreach($_FILES['files']['tmp_name'] as $key => $name_tmp){
        $file = $_FILES['files']['name'][$key];
        $tmpnm = $_FILES['files']['tmp_name'][$key];
        $type = $_FILES['files']['type'][$key];
        $size = $_FILES['files']['size'][$key];
        $dir = "file/".$file;
        $move = move_uploaded_file($tmpnm, $dir);
if ($move){             

            $query = ("INSERT into dfile VALUES(null,'$file','$type','$size')");
            $result = $dbLink->query($query);

            if($result){
                echo "<h4>Upload Complete</h4></br>";

            }else{
                echo "Error Table DB";

            }

        }
 }

}

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

SomePage.php

<a href="download.php?FileNo=<?echo $FileNo;?>" rel="nofollow noreferrer noopener">File Name</a>

download.php

$FileNo=$_GET['FileNO'];

//Use Mysql Query to find the 'full path' of file using $FileNo.
// I Assume $FilePaths as 'Full File Path'.

download_file($FilePaths);

function download_file( $fullPath )
{
  if( headers_sent() )
    die('Headers Sent');


  if(ini_get('zlib.output_compression'))
    ini_set('zlib.output_compression', 'Off');


  if( file_exists($fullPath) )
  {

    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);

    switch ($ext) 
    {
      case "pdf": $ctype="application/pdf"; break;
      case "exe": $ctype="application/octet-stream"; break;
      case "zip": $ctype="application/zip"; break;
      case "doc": $ctype="application/msword"; break;
      case "xls": $ctype="application/vnd.ms-excel"; break;
      case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
      case "gif": $ctype="image/gif"; break;
      case "png": $ctype="image/png"; break;
      case "jpeg":
      case "jpg": $ctype="image/jpg"; break;
      default: $ctype="application/force-download";
    }

    header("Pragma: public"); 
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false); 
    header("Content-Type: $ctype");
    header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" );
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".$fsize);
    ob_clean();
    flush();
    readfile( $fullPath );

  } 
  else
    die('File Not Found');

}

Solution 2

The path depends on the structure of your scripts but basically it will go like this :

while($row = $result->fetch_assoc()) { 
  echo " <tr> 
  <td>{$row['comp']}</td> 
  <td>{$row['expire']}</td> 
  <td>{$row['file']}</td> 
  <td>{$row['size']}</td>
  <td>
    <a download href=\"file/{$row['file']}\">Download this file</a>
  </td>
  </tr>";
}

Solution 3

You do this, by setting headers:

<?php

$file = $_GET['file'];
$dir = '';

if(isset($_GET['file']) && file_exists($dir . $file)) {
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $type = $finfo->file($file); // get MIME-Type
    header("Content-Type: " . $type);
    header("Content-Disposition: attachment; filename=\"" . $file . "\"");
    readfile($dir . $file);
}

Be sure that the Content-Type is a MIME-Type. You could put this code in a seperate file dl.php and call it like this in your view:

<a href="dl.php?file=path/to/your/file.txt" rel="nofollow noreferrer noopener">Download</a>

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply