I. index. php :? Phpechoahrefprocess. php? Filenamehalo.mp3 download? In process. php :? Phpheader (Content-type: applicationoctet-stream); header (Content-Disposition: attachment; filename. basename ($ _ GET [filename]).); header (Cont
I. index. php :? Php echo a href = 'process. php? Filename=halo.mp3 'download/? In process. php :? Php header (Content-type: application/octet-stream); header ('content-Disposition: attachment; filename = '. basename ($ _ GET ['filename']). ''); header (Cont
I,
Index. php:
In process. php:
This is the simplest method, but there is a problem: if the request path contains Chinese characters, the downloaded file name may be garbled.
II,
For the solution to the above problem, in index. php:
In process. php:
If the output is Apache + PHP, it must be sent to the Apache output buffer before being sent to the user. For Nginx + fpm, if they are deployed separately, additional network IO will be introduced.
III,
It seems that there is no problem now, but there is still a problem with readfile. Although PHP readfile is trying to achieve as efficient as possible, it does not occupy the PHP memory, but in fact, it still needs to use MMAP (if supported), or a fixed buffer to read files cyclically and output directly.
So can we bypass the PHP layer and directly send files to users by webserver? Yes. We can use the module mode_xsendfile of Apache to send the file directly to the user.
Code implementation: (process. php)
Header ("Content-type: application/octet-stream"); // process the Chinese file name $ ua = $ _ SERVER ["HTTP_USER_AGENT"]; $ encoded_filename = urlencode ($ _ GET ['filename']); $ encoded_filename = str_replace ("+", "% 20", $ encoded_filename ); if (preg_match ("/MSIE/", $ ua) {header ('content-Disposition: attachment; filename = "'. $ encoded_filename. '"');} else if (preg_match ("/Firefox/", $ ua) {header (" Content-Disposition: attachment; filename * = \ "utf8 ''". $ _ GET ['filename']. '"');} else {header ('content-Disposition: attachment; filename = "'. $ _ GET ['filename']. '"');} // Let Xsendfile send the file header (" X-Sendfile: $ _ GET ['filename'] ");
Finally, if you want to, you can determine the suffix first, because sometimes it is inconvenient to download images as files:
$ Type = strrchr ($ _ GET ['filename'], ". "); // obtain the suffix if ($ type =" jpg "|" png "|" gif ") {header (" Content-Disposition: filename = $ _ GET ['filename'] "); // I tried it here. If it is enclosed in quotation marks, the header (" Content-Type: image/$ type ");}