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

readfile($filename);

//Read and stream the file

}else{

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

}

Leave a Reply

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


three × = 18

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>