Protect Uploaded Files by .htaccess and Download using PHP Header

Using the internet to share the data, chat with friends or colleagues via social media is a common activity at this time. And people are not ignorant to upload or download a file through the Internet to share with many people who are connected.  On this occasion I will share about how to protect a file that is uploaded using .htaccess so that users can not download directly.
Previously I have discussed how to filter the files that are uploaded by users based on file type and file size in the article Validate Input File From HTML Form Using PHP.  I will explain a little about what the .htaccess file, .htacces file is the configuration file provided by the Apache web server, which is where this file is used to change the default settings of the Apache server. Because of the large web hosting using Apache, it is necessary to understand about the use of .htaccess for webmasters.

In this article I will take an example to protect files with the extension .pdf, .xls, .xlsx, .doc and .docx,
The following code to your .htaccess file:
 Options -Indexes
<FilesMatch ".(pdf|xls|xlsx|doc|docx)$">
 Order Allow,Deny
 Deny from all
</FilesMatch>
To create a .htaccess file you can open notepad copy the code above then save as, change the Save as type to all files (*. *) and ANSI encoding, give .htaccess filename, then save it in the directory where uploaded files will be placed. It should be noted that the code in the .htaccess file should be written in a single line, so if using notepad sure wordwrap format in notepad inactive.


Create HTML FORM To Adding Files Upload And Display the Uploaded File

To upload a file needed an interface that is an HTML form where the form will ask the user to take a picture of a computer, then upload it by pressing the submit button. To create a file upload interface, type the script below.

Filename: index.php
<html>
 <head>
   <title>Upload Download Application</title>
 </head>
 <body>
<b>Upload Your Files</b><br><br>
  <form method="POST" action="upload.php" enctype="multipart/form-data">
  File : <input type="file" name="file_upload"><br><br>
  <input type="submit" name="submit" value="Upload">
  </form>
  <table border="1" cellpadding="0" cellspacing="0">
   <tr>
    <td>&nbsp;</td><td><b>Filename</b></td><td><b>Filesize</b></td><td><b>Link</b></td></tr>
    <?
    $dir = opendir ("files/");
    $count=0;
    while (false !== ($file = readdir($dir))) {
        if (strpos($file, '.pdf',1)||strpos($file, '.xls',1)||strpos($file,'.xlsx',1)||strpos($file,'.doc',1)||strpos($file,'.docx',1)) {
          $filesize=round(filesize("files/".$file)/1024);
          $count++;
          echo "<tr><td>".$count."</td><td>".$file."</td><td>".$filesize." KB</td><td><a href=\"download.php?file=".$file."\">Download</a></td></tr>";           
        }
    }
    ?>
  </table>

 </body>
</html>
After type the script above save the file with filename index.php. When running the script above would look like the look in the picture below.
 
Create a Script to filter and Uploading Files

After you create the interfaces to retrieve files from the computer, it is time to make the script to upload files to the server. Consider the code snippet below.

Filename : upload.php
<?
$err_msg="";
if(isset($_FILES['file_upload']['name'])){
  if(!empty($_FILES['file_upload']['name'])){
     $allowed_files=array(1=>"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                          2=>'application/excel',
                          3=>'application/msword',
                          4=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                          5=>'application/pdf',
                          6=>'application/force-download');   
     if(in_array($_FILES['file_upload']['type'],$allowed_files)){
        $max_allowed_size=5000000;
        if($_FILES['file_upload']['size'] <= $max_allowed_size){
          $upload_dir="files/";
          move_uploaded_file($_FILES['file_upload']['tmp_name'],$upload_dir.$_FILES['file_upload']['name']);
          header("location:index.php");
        }
        else{
          $err_msg="<span style=\"color:#FF0000;\">Please upload file no more than 5MB!</span>";
        }
     }
     else{
       $err_msg="<span style=\"color:#FF0000;\">Please fill the upload form with the pdf, word or excel files!</span>";
     }                      
  }
  else{
    $err_msg="<span style=\"color:#FF0000;\">Please fill the form with your file that want to upload</span>";
  }
}
else{
  $err_msg="<span style=\"color:#FF0000;\">Please fill the form with your file that want to upload</span>";
}
?>
<html>
 <head>
   <title>Upload Download Application</title>
 </head>
 <body>
  <? echo $err_msg;?><br/>
  <form method="POST" action="upload.php" enctype="multipart/form-data">
  File : <input type="file" name="file_upload"><br><br>
  <input type="submit" name="submit" value="Upload">
  </form>
 </body>
</html>
After you type the code above, then save it with the name of file is upload.php, this file must be located one folder with the index.php file. The above script will perform a filter against the file sent by the user before saving it on the server. Previously, you must create a folder called "files" and put the .htaccess file to protect the files upload in this folder, the folders "files" must be located one folder with the index.php file.

Create Script to Download Files Using PHP Header

Next is to make a script to download the files, because the files that are uploaded by users have been protected by .htaccess then there can not be downloaded directly to the url of that file. So you need to create a php script to download the files. You can find the PHP script to download the file below.

Filename : download.php
<?
if(isset($_GET['file'])){
 $file=$_GET['file'];
 $path="files/";
 $fullpath=$path.$file;
 $f_type=pathinfo($fullpath,PATHINFO_EXTENSION); 
 $allowed_type=array(1=>"pdf",
                     2=>"doc",
                     3=>"docx",
                     4=>"xls",
                     5=>"xlsx");
 if(in_array($f_type,$allowed_type)){                   
   if ($open = fopen ($fullpath, "r")){
      header("Content-Type: application/force-download");
      header("Content-Transfer-Encoding: binary");
      header("Content-Length:". filesize($fullpath));
      header("Content-Disposition: attachment; filename=\"".$fullpath."\"");
      while(!feof($open)) {
            $buffer = fread($open, 2048);
            echo $buffer;
      }
      fclose ($open);
   }
 }
}
?>
After you have completed the above code type and then save the file with the name download.php.  You can download the above script in order to better facilitate. Click the download link below.

Download Source