The server provides a file download, typically using a URL pointing to a file in the server to provide downloads.
But this can not be statistics, permission detection and other operations.
Therefore, the general use of PHP to provide downloads, the code is as follows:
<?php
$file = ' test.zip ';
if (file_exists ($file)) {
header (' Content-type:application/octet-stream ');
Header (' Content-disposition:attachment filename= '. basename ($file));
Header (' Content-length: ' FileSize ($file));
ReadFile ($file);
>
process Chinese file name:
<?php
$file = ' test.zip ';
$filename = ' Chinese. zip ';
if (file_exists ($file)) {
$user _agent = $_server[' http_user_agent '];
$encode _filename = Rawurlencode ($filename);
if (Preg_match ("/msie/", $user _agent)) {
header (' content-disposition:attachment; filename= '. $encode _filename. ' ");
}else if (Preg_match ("/firefox/", $user _agent)) {
header ("content-disposition:attachment; Filename*=\ "UTF8" ". $filename. '");
} else{
Header (' Content-disposition:attachment filename= "'. $filename. '");
}
ReadFile ($file);
>
Use PHP ReadFile, need to go through the PHP layer, if you can directly through Apache to send files to the user, not through the PHP layer, will improve download speed.
use Apache mod_xsendfile, download address: mod_xsendfile, let Apache send files directly to users
Installation:
sudo apxs2-cia mod_xsendfile.c
sudo a2enmod xsendfile
sudo/etc/init.d/apache2 Restart
APXS2 is used to compile the Apache module, and you need to install Apache2-dev
Set Xsendfile Open:
<Directory>
xsendfile on
</Directory>
The code is as follows:
<?php
$file = ' test.zip ';
$filename = ' Chinese. zip ';
if (file_exists ($file)) {
$user _agent = $_server[' http_user_agent '];
$encode _filename = Rawurlencode ($filename);
if (Preg_match ("/msie/", $user _agent)) {
header (' content-disposition:attachment; filename= '. $encode _filename. ' ");
}else if (Preg_match ("/firefox/", $user _agent)) {
header ("content-disposition:attachment; Filename*=\ "UTF8" ". $filename. '");
} else{
Header (' Content-disposition:attachment filename= "'. $filename. '");
}
Header (' X-sendfile: '. $file);
}
? >