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


Liked It? Get Free updates in your Email

Delivered by feedburner

7 thoughts on “PHP force file download

  1. rakesh
    #

    yes it is working

    Reply
  2. nonzo53
    #

    Thanks. A lot it worked for me

    Reply
  3. partha
    #

    thanks a lot

    Reply
  4. Hari Prasad
    #

    Sunny

    The Only thing i Can Say U Is U ROCK

    Thank You It Was Vary Help full

    Once Again Thank U Man

    Reply
  5. Robert
    #

    size file is zero during force download?

    Reply
  6. devinder
    #

    unable to download pdf files, but working jpg’s

    Reply

Leave a Reply

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