How to Force Download a File With PHP

In this tutorial, we are going to see how to force download a file using PHP. Generally, we don’t need to add any PHP script to download any type of file.

Using an anchor tag with download attribute and file source allows downloading files easily.

In PHP programming language, we can force to download a file using readfile() function. You can download any file format using this script.

View Demo   

[sociallocker]Download Script [/sociallocker]

Download a File in PHP

<?php
$filename = "abc.txt";
$filepath = "files/" . $filename;

//check for file not exist
if (!file_exists($filepath)) {
    die("File not found");
}

//force download 
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header('Content-Disposition: attachment; filename="' . basename($filepath) . '"');
readfile ($filepath);   
exit(); 
?>

In above script

header('Content-Disposition: attachment; filename="' . basename($filepath) . '"');

is used to display browser save as dialog box

readfile ($filepath);  

is used to output a file (mean read a file and write it to the output buffer).

Leave a Comment