PHP File Download instance code analysis,
The file download function is basically essential for a website. Let's take a look at how PHP implements file download today.
Uncontrolled type
The uncontrolled type here refers to the types of resources that can be directly downloaded without adding PHP code control. In general, compressed file .rar; audio and video files:. avi can also be directly downloaded. However, the audio and mp4 files are directly parsed and played by the browser.
For example:
. Avi file
. Rarfile
. Mp4, MP3, ImageWill be parsed directly.
Core code
It is easy to use php code to control file downloads. We need very little code to complete such complicated work.
Type
// Use the basename function to obtain the file name, not the path information, and protect the server's Directory Security header ("content-disposition: attachment; filename =". basename ($ filename ));
Length
Header ("content-length:". filesize ($ filename ));
Implementation Functions
<? Php $ filename = $ _ GET ['filename']; // you can use the basename function to obtain the file name rather than the path information, which protects the server's Directory Security header ("content-disposition: attachment; filename = "$ filename); header (" content-length :". filesize ($ filename); readfile ($ filename);?>
Optimization
When the file name is specified above, we do not use a function named basename. Therefore, when downloading the file, the complete path of the file on the server will be associated.
Note:The name of the downloaded file must not contain the full path name on the server. Otherwise, some resources may be leaked. Even if there is a way to control the permission to access resources, it is good to use the basename function.
Name of the original downloaded file
Optimized File Download name
Summary
PHP File Download is really convenient than Java implementation. There is a lot of information provided to us within the downloaded file. Through the encapsulated information, we can implement a more elegant File Download System.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.