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= ' abc.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:
1, the file download speed limit to 31.2kb/s, that is, only send 20.5kb per second to the client file stream, 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.
2, the technical aspect , first adds the header file, declares Content-type as Application/octet-stream, indicates that the request will send in the stream way, and declares the content-length, namely declares the file stream the 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.
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.
The above implementation of the PHP limit file download speed function, I hope this article on the PHP program to help you.