PHP Force Browser To Download A File Instead Of Viewing It

PHP Force Browser To Download A File Instead Of Viewing It

Have you ever tried to get your user to download a file, and then realized when testing yourself that modern browsers don’t actually download the file now? Instead, they prioritize allowing the user to view the file. This applies to file extensions such as pdf, mp4, and many others

Here’s the solution. Just redirect the download link of your file to a PHP file that forces your user to download the file instead of viewing it. This can be done as PHP, a server-side language, allows you to modify the headers sent to the browser.

Firstly, make sure you modify your download links to redirect to the new PHP file, as shown below

Before:

<a href='https://file.com/download.mp4'></a>

After:

<a href='https://file.com/ForceDownload.php?url=https://file.com/download.mp4"></a>

Note: you should encode the url query value. If you are using PHP, you can do so by doing something like

$string = "<a href='https://file.com/ForceDownload.php?url=".urlencode('https://file.com/download.mp4')."'></a>";

The solution is as shown below. This is the PHP file, namely, ForceDownload.php, that forces the download onto your user’s browser

<?php
$file_url = urldecode($_GET['url']);
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
readfile($file_url);

exit;
?>

 

Enjoyed the content ? Share it with your friends !