Tuesday, 18 February 2014

PHP force download pdf, csv, image, text, zip

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

<?
1:  $file="/path/to/file" //file location
2:  header('Content-Type: application/octet-stream');
3:  header('Content-Disposition: attachment;
4:  filename="'.basename($file).'"');
5:  header('Content-Length: ' filesize($file));
6:  readfile($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.

 

No comments:

How calulation total value for HTML input text?

<script> $j(document).ready(function(){ $j(":text").keyup(function(){ if (isNaN($j(this).val())) { alert(...