Php file download (which can limit the download speed) implementation code. In php, file downloading will take advantage of three main functions: headerfopenfread. There are also some auxiliary functions such as determining whether the file exists file_existsis_file, next, let's take a look at the three main functions of header fopen fread when downloading a file in php. There are also some auxiliary functions such as determining whether the file exists with file_exists is_file, next, let's take a look at an instance that can limit the download speed.
In the php Tutorial, three main functions of header fopen fread are used for file downloading. There are also some auxiliary functions such as file_exists is_file in file judgment, next, let's take a look at an instance that can limit the download speed.
*/
$ File = "testbench"; // file to be sent to the client
$ Speed = 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.
The result of this function is that the echo output data is continuously displayed on the page.
For ($ I = 10; $ I> 0; $ I --)
{
Echo $ I .'
';
Ob_flush ();
Flush ();
Sleep (1 );
}
Ob_end_flush ();
Sleep
The sleep () function delays code execution for several seconds.
Header
The header () function sends the original http header 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 later versions, you can use the output cache to solve this problem):
Filesize: get the file size.
Fread reads the file content opened by fopen
Javasfopen fread has three main functions, and there are also some auxiliary functions such as determining whether the file exists file_exists is_file. let's take a look at a file...