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.

Force Download Files in PHP

Sometimes, we need to force download files in the user’s browser for better user experience. However, there is no direct way to download files forcefully. The only way we can force download a file in a browser is by using a server-side language. Here, we will learn how to force download files using PHP.

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 a “download.php” file on your server and write the 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 the above PHP code, add your file path and give it a link 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

Conclusion

Here, we learned how to download any file using PHP forcefully. I hope now you can force download files in your PHP project.

Enjoy Programming πŸ™‚

Leave a Reply

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