Force Download A File From Server In PHP

In this post, we are going to see how to force download a file in PHP. Well, we can easily put an anchor link with the file path to be downloaded. Then why we are going to do it using PHP?

Using the normal anchor link with file path is publicly open and the file path can be found easily. But if we force download a file using PHP, then the file path will be hidden. So, for security reason sometimes PHP for download is necessary. But in those cases where there is no problem to let users know the file path, then it is okay to use the simple anchor link to let people download the file with that link. But in many cases, it is better to use PHP to let peoples download your file.

Generate PDF from HTML template in PHP using Dompdf

Upload File With Ajax Using PHP and jQuery

PHP code to forcefully download a file

Below is our PHP code to force download a file from the server:

<?php
$file_path = 'path_to_file/dummy_file.zip';
$filename = 'downloaded_file.zip';

header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$filename."\""); 
echo readfile($file_path);
?>

In the above code, first, we take the file path and give a new file name and then use PHP header to define the content type, content transfer, and content disposition. After that, we have used PHP readfile() function and send the file path as the parameter.

How to send email using PHP mail() function?

Now if we browse our PHP file that contains with the above PHP code and the file in that path then we will see that forcefully the file downloaded and the filename is as we defined in the variable within the code. In this case, we will see our downloaded file name is “downloaded_file.zip”.

So we have seen the code which forces downloading a file in PHP.

 

Leave a Reply

Your email address will not be published. Required fields are marked *