Sometimes you want to download directly when clicking the corresponding link instead of displaying it on the web page, then you need to forcefully set the header information.
Share a piece of PHP function implementation code that does not produce garbled characters to achieve forced downloading of files.
Example, PHP code to implement forced downloading of files.
-
-
- /**
- * Downloader
- *
- * @param $file
- * path to the file
- * @param $downloadfilename
- * (null|string) the name you want to use for the file to be downloaded.
- * (if you don't specify it use current file name)
- *
- * @return file stream
- */ bbs.it-home.org
- function download_file($archivo, $downloadfilename = null) {
- if (file_exists($archivo)) {
- $downloadfilename = $downloadfilename !== null ? $downloadfilename : basename($archivo);
- header('Content-Description: File Transfer');
- header('Content-Type: application/octet-stream');
- header ('Content-Disposition: attachment; filename=' . $downloadfilename);
- header('Content-Transfer-Encoding: binary');
- header('Expires: 0');
- header('Cache-Control: must- revalidate, post-check=0, pre-check=0');
- header('Pragma: public');
- header('Content-Length: ' . filesize($archivo));
- ob_clean();
- flush ();
- readfile($archivo);
- exit;
- }
- }
Copy code
|