Home >Backend Development >PHP Tutorial >PHP file download (can limit download speed) implementation code_PHP tutorial

PHP file download (can limit download speed) implementation code_PHP tutorial

WBOY
WBOYOriginal
2016-07-20 11:09:09909browse

File downloading in php will use three main functions: header fopen fread, and there are also some auxiliary functions such as judging the existence of a file file_exists is_file and other functions. Let's look at an example of file downloading that can limit the download speed

in php tutorial File downloading will use three main functions: header fopen fread, and there are also some auxiliary functions such as functions to determine the existence of files such as file_exists is_file. Let’s look at an example of file downloading that can limit the download speed

*/
$file = "test.mp3"; // file to be sent to the client
$speed = 8.5; // 8,5 kb/s download rate limit
if(file_exists( $file) && is_file($file)) {
header("cache-control: private");
header("content-type: application/octet-stream"); ​​
header("content -length: ".filesize($file));
header("content-disposition: filename=$file" . "%20");
flush();
$fd = fopen($ file, "r");
while(!feof($fd)) {
echo fread($fd, round($speed*1024));
flush();
sleep( 1);
}
fclose ($fd);
}

/*
flush
The flush function refreshes the buffer of the php program to implement echo dynamic output
this The result of the function implementation is that the page continuously displays the data output by echo
for ($i=10; $i>0; $i--)
{
echo $i.'
ob_flush();
flush();
sleep(1);
}
ob_end_flush();

sleep
sleep () function delays code execution for a number of seconds. The
header
header() function sends raw http headers to the client.

It is important to realize that the header() function must be called before any actual output is sent (in PHP 4 and above, you can use output caching to solve this problem):


filesize Get the file size
fread Read the content of the file opened by fopen


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/444821.htmlTechArticleFile downloading in php will use three main functions: header fopen fread, and there are also some auxiliary functions such as judgment Files exist such as file_exists is_file and other functions. Let’s look at a file...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn