Home

How to Force Download a File With PHP

Published on 2nd Mar 2018 in 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 file. Using an anchor tag with download attribute and file source allows to download file easily. In PHP programming language, we can force to download a file using readfile() function. You can download any file format using this script.

How to Force Download a File With PHP

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).

Share It
Stay Connected
Like Us on Facebook