PHP file download speed limit sample code

Speed ​​limit download sample code
<?php
// local file that will be sent to client
$local_file='abc.zip';
// file name
$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 the current part of the file to the browser flush();// Flush the content output to the browser sleep(1);// The terminal will continue after 1 second }











fclose($file);// Close the file stream
}else{ die('Error: The file '.$local_file.' does not exist!'); } Code interpretation The default download speed limit in the code is 31.2kb/s, that is, per second Only 20.5kb of the file stream is sent to the client until the entire file is sent.



Before use, you need to add a header file, declare the Content-Type as application/octet-stream, indicating that the request will be sent as a stream, and declare the Content-Length, which declares the size of the file stream.

Flush() is used in the code. The function of the flush function is to refresh the buffer of the PHP program and realize the dynamic output of print.

Guess you like

Origin blog.csdn.net/winkexin/article/details/131351852