How to Force Download File Using PHP

Generally, we can download files directly by creating hyperlinks. But Images, PDFs and Media files open in a browser rather than downloading.


<!DOCTYPE html>
        <title>HTML Download HyperLinks</title>
	<a href="/downloads/">Download Zip file</a>
	<a href="/downloads/temp.pdf">Download PDF file</a>
	<a href="/downloads/temp.jpg">Download Image file</a>

In the above HTML code snippet, we can see that “” will be downloaded automatically in the browser but “temp.pdf” and “temp.jpg” will open in the browser rather than downloading.

To solve this problem, we can use PHP to force download any file.

Just create “download.php” file on your server and write below code in it.


  //file path in server
  $file_path = "file_path/file_name";
  // check if file exist in server
  if(file_exists($file_path)) {
      header('Content-Description: File Transfer');
      header('Content-Type: application/octet-stream');
      header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
      header('Expires: 0');
      header('Pragma: public');
      header('Content-Length: ' . filesize($file_path));
      // Clear output buffer
    echo "File not found.";

In above PHP code, add your file path and give this file link as to download link. You can use the above code and make it more advance to download multiple files with a single “download.php” file.

You can change the content-type header for different media types.

Also read: How to Upload File in PHP

Leave a Reply

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

Read previous post:
replace all javascript
How to Replace All Words in a String Using JavaScript

We can use replace() function in JavaScript to replace all the words in the given string. replace() method in JavaScript...