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!”;
}