It is common to server downloadable files which are located outside the public folder by PHP:
$fp = fopen($file,"r") ;
header("Content-Type: application/msword");
header('Content-Disposition: attachment; filename="'.$filename.'"');
while (! feof($fp)) {
$buff = fread($fp,4096);
echo $buff;
}
I have two questions:
-
Comparing with static files served by web server (direct file URL); does this method needs more resources (memory and cpu), as PHP needs to read the file and deliver?
-
How we can display some text on the page? As we defined
header, we do not have html output of the php script.
1 Since you have to process the file with this script it require more
resources than just normal download link. However this is depend on your needs. If you think these files need more security. Let’s say only authenticated users can download the file and only the file belongs to him. Then you need to validate those. In such situation you need the code you have put in your question. If your files are open to the public then you can display direct link to the file may be locating them somewhere in public temporarily.
2 I can suggest you two methods to perform this.
Method 1 :
You need javascript support to perform this kind of requirement in handy way. Assume you need to display some HTML on the page where the download is possible. You can create a page with the HTML you want and you can put a download button.
<input type="button" name="cmdDownload" id="cmdDownload" value="Download" onclick="downloadFile('<?php echo $pathToTheFile; ?>');" />And you can keep hidden iframe to process the download.
Assume your PHP download page is download.php.
Then you can have a javascript function like this.
Method 2:
Other than above method you can use META Refresh as well.
You can have HTML display with this too.