php forces the download of type implementation code

  • 2020-05-05 10:59:30
  • OfStack

 
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 hyperlinking them to reduce hotlinking! Give the file to the browser and ask the browser to download

Take txt type for example

Because the current browser can already recognize the txt document format, if you only make a text link to the txt document, you will only open a new window to display the contents of the txt file after clicking, which will not achieve the purpose of clicking to download. Of course, the solution to this problem could be to rename the txt file to a file that the browser does not recognize (such as rar). In this case, the browser cannot recognize the rar file, so the user has to download it. Another option is to use the code to format the document with header for the purpose of clicking to download.
The code for PHP is as follows:
 
$filename = '/path/'.$_GET['file'].'.txt'; // The file path  
header("Content-Type: application/force-download"); 
header("Content-Disposition: attachment; filename=".basename($filename)); 
readfile($filename); 

Brief description:
The first header function sets the value of Content-Type to application/ force-download.
The second header function sets the file to be downloaded. Note that filename does not contain the file name of the path. The value of filename will be the file name in the popup dialog box after downloading. If there is a path, the file name of the popup dialog box is unknown.
Finally, through the readfile function, the file stream output to the browser, so that the txt file download.

Related articles: