PHP force file download

By default most of the file types (eg: txt, jpg, png, gif, html, pdf, etc.) displayed in browser instead of download. But we can force browser to download these files instead of showing them. In this article I will explain how to force file download in php.

Php code to force file download

$file="/path/to/file" //file location 
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"'); 
header('Content-Length: ' . filesize($file));

How it works?

Third line forces browser to download file. Fourth line sends the file name to save it may be different from original filename. Fifth line sends file size header to browser. And finally sixth one outputs file content to download stream.

Published by Sunny

A Mechanical engineer by education and web developer by passion and profession. He lives in Lucknow, India. Currently earning his livings by hitting keyboad. ;)

Join the Conversation


Leave a comment

Your email address will not be published. Required fields are marked *