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.

Example:

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

In the above HTML code snippet, we can see that “temp.zip” 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.

download.php

<?php
  //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
      flush();
      readfile($file_path);
      exit();
  }else{
    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...

Close