Generally, we can download files directly by creating hyperlinks. But Images, PDFs, and Media files open in a browser rather than downloading.
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.
<?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
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 🙂
There is a reason big-name companies like CNN use WordPress. WordPress is a popular content…
In this tutorial, I'm going to show you how to install MySQL on your computer.…
Download Turbo C++ for windows 10 in just 7 Mb and run your first C++…
We can redirect any webpage to any other or redirect the whole domain or website…
There are lots of methods to redirect pages, like refresh-redirect from META tag, redirect from…
Include files in PHP are used in appending various global or config files. We can…