Sometimes you may want to slow down the download file for some reason, such as you would like to implement the file download progress bar function. The biggest advantage of limiting download speed is that it saves bandwidth and avoids the network jam caused by excessive instantaneous traffic. This article will share with you how to implement the download speed of restricted files through PHP code.
First take a look at the code that restricts file download speed with PHP:
<?php
//will be sent to the client's local file
$local _file= ' www.Alixixi.com.zip ';
FileName
$download _file= ' your-download-name.zip ';
Set download rate (=> 31.2 kb/s)
$download _rate=31.2;
if (file_exists ($local _file) &&is_file ($local _file)) {
header (' cache-control:private ');/Send Headers
header (' Content-type:application/octet-stream ');
Header (' Content-length: ' FileSize ($local _file));
Header (' content-disposition:filename= '. $download _file);
Flush ()//refresh content
$file =fopen ($local _file, "R");
while (!feof ($file)) {
print fread ($file, round ($download _rate*1024));//Send current part of file to Viewer
Flush ();//Flush Content output to browser-side sleep
(1);//terminal 1 seconds to continue
}
fclose ($file);//close file stream
}else{
die (' Error: File '. $local _ File. ' does not exist! ');
Here's some analysis of the above code:
The above example limits the file download speed to 31.2kb/s, which sends only 20.5kb of file streams per second to the client until the entire file is sent. If this limit is not available, then the file will be sent to the client in the form of a stream, how much will be sent, what happens? If the file size is 2m, then all of a sudden to the 2m data circulated to the past, this will likely lead to network congestion and interrupt the execution of the script, this download method can not be used in practical applications.
Technically, you first add a header file, declare Content-type as Application/octet-stream, indicate that the request will be sent as a stream, and declare content-length, which declares the file flow size. The flush () is used in the code, and the flush function is to refresh the buffer of the PHP program and realize the print dynamic output.
Note whether the above check file exists is through file_exists this function, but this function can only check relative to the current server Web directory inside the file, if the remote files on the Internet, you can use this site as follows this article:
PHP to determine whether a remote file exists
To check if the file exists.
Another reminder is: clever use of the above code, but also to achieve the client display file download progress bar function, interested friends can try, here will not write more.