HomeDefault

Force file download using PHP script and HTTP headers

Like Tweet Pin it Share Share Email

Force file download using PHP algorithm

 

It is very frustrating to click on a link to a document you want to read, and then have to wait for it to download and finally it open on your computer/browser, but you had expected it to download. It is mainly for some file types as (eg: txt, jpg, png, gif, html, pdf, etc.)

 

If you have a file and want it to make available for people to download? If it is an HTML file or a PDF, you can’t just post link, as the web browsers open those automatically, instead you need to do some trickery using PHP script and below is the same, hope it will help you a lot.

 

PHP allows you to change the HTTP headers of files that you’re writing, so that you can force a file to be download. This is perfect for files like PDFs, document files, images, and video that you want your customers to download rather than open it in browser for view.

 


<?PHP

// Define the path to file,you want to make it downloadable
$file = 'articles_file.zip';

if(!$file)
{

// File doesn't exist, output will show error
die('file not found');

}
else
{

// Set headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");

// Read the file from disk
readfile($file);

}
?>

Comments (1)

  • i m geting the pdf generated succesfully but where it is generated i m not getting visible..

Comments are closed.