How to force download files in PHP

Spread the love

In my previous post “How to force download pdf files in PHP“, I explained how to download the pdf files forcefully. Thought of creating a generic script to download any file type by slightly modifying the script.

<?php
if(isset($_REQUEST["path"])){
    $file_url = urldecode($_REQUEST["path"]);
    header('Content-Type: application/octet-stream');
    header('Content-Transfer-Encoding: Binary');
    header('Content-Disposition: attachment; filename="'.basename($file_url).'"');
    readfile($file_url);
}
?>

You can try a quick demo using this link which opens the image within the browser.

And using the above script, following demo link will download the same file instead of opening it in browser.