How to stream a file as attachment in PHP

Sometimes we need to download files as attachment in PHP. This code can ideally be called on a hyperlink.

$filename = “myImage.jpg”;

if(file_exists($filename)) {

header(“Content-disposition: attachment; filename={$filename}”);

//Tell the filename to the browser

header(‘Content-type: application/octet-stream’);

//Stream as a binary file! So it would force browser to download


//Read and stream the file


echo “Sorry, the file does not exist!”;


Leave a Reply

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

4 + = seven

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>