Php forcibly downloads the code of a specified type of file
- // Download prompt
- // Site http://bbs.it-home.org
- Function downloadFile ($ file ){
- /* Coded by Alessio Delmonti */
- $ File_name = $ file;
- $ Mime = 'application/force-download ';
- Header ('pragma: public '); // required
- Header ('expires: 0'); // no cache
- Header ('cache-Control: must-revalidate, post-check = 0, pre-check = 0 ');
- Header ('cache-Control: private ', false );
- Header ('content-Type: '. $ mime );
- Header ('content-Disposition: attachment; filename = "'. basename ($ file_name ).'"');
- Header ('content-Transfer-Encoding: binary ');
- Header ('connection: close ');
- Readfile ($ file_name); // push it out
- Exit ();
- }
- ?>
Php downloads files instead of hyperlinks, which can reduce leeching! Send the file to the browser for download. Take the txt type as an example To avoid the direct opening of txt files in the browser, you can rename the txt file as a file (such as rar) that the browser does not know. in this case, the browser cannot recognize rar files, you can only download the file. The above method is sometimes not applicable. We use another method to set the document format through the header information of the php file to achieve the purpose of clicking download. Example:
- // Download the php header function
- // Site bbs.it-home.org
- $ Filename = '/path/'.w._getw.'file'{.'.txt'; // file path
- Header ("Content-Type: application/force-download ");
- Header ("Content-Disposition: attachment; filename =". basename ($ filename ));
- Readfile ($ filename );
- ?>
Note: the first header function sets the Content-Type value to application/force-download; the second header function sets the file to be downloaded. Note that the filename here is a file name that does not contain a path. The value of filename will be the file name in the pop-up dialog box after you click Download. if there is a path, the file name in the pop-up dialog box is unknown; finally, the readfile function outputs the file stream to the browser to download the txt file. |