-
- /**
- * Safe download of general files
- * edit bbs.it-home.org
- */
- $durl = 'file/phpcms2008_o2abf32efj883c91a.iso';
- $filename = 'phpcms2008_o2abf32efj883c91a.iso';
- $file = @fopen ($durl, 'r');
- header("Content-Type: application/octet-stream");
- header("Accept-Ranges: bytes");
- header("Accept-Length: ".filesize($durl));
- header("Content-Disposition: attachment; filename=".$filename);
- echo fread($file,filesize($durl));
- fclose($file);
- ?>
Copy code
When the above code encounters a large file that exceeds the maximum memory value configured in php.ini, the server will occupy a lot of CPU resources and the file cannot be downloaded normally, and only files of dozens of Kb can be downloaded.
This can be solved with the following code:
-
- /**
- * Implementation code for safe downloading of large files
- * edit bbs.it-home.org
- */
- function download($url, $filename) {
- // Get the file size, prevent files exceeding 2G, use sprintf to read
- $filesize = sprintf ( "%u", filesize ( $url ) );
- if (! $filesize) {
- return;
- }
- header ( "Content-type:application/octet-streamn" ); //application/octet- stream
- header ( "Content-type:unknown/unknown;" );
- header ( "Content-disposition: attachment; filename="" . $filename . """ );
- header ( 'Content-transfer-encoding: binary ' );
- if ($range = getenv ( 'HTTP_RANGE' )) { // When there is an offset, use the breakpoint resume header of 206
- $range = explode ( '=', $range );
- $range = $range [1];
-
- header ( "HTTP/1.1 206 Partial Content" );
- header ( "Date: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
- header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s", filemtime ( $url ) ) . " GMT" );
- header ( "Accept-Ranges: bytes" );
- header ( "Content-Length:" . ($filesize - $range) );
- header ( "Content-Range: bytes " . $range . ($filesize - 1) . "/" . $filesize );
- header ( "Connection : close" . "nn" );
- } else {
- header ( "Content-Length:" . $filesize . "nn" );
- $range = 0;
- }
- loadFile ( $url );
- }
-
- function loadFile($filename, $retbytes = true) {
- $buffer = '';
- $cnt = 0;
- $handle = fopen ( $filename, 'rb' );
- if ($handle === false) {
- return false;
- }
- while ( ! feof ( $handle ) ) {
- $buffer = fread ( $handle, 1024 * 1024 );
- echo $buffer;
- ob_flush ();
- flush ();
- if ($ retbytes) {
- $cnt += strlen ( $buffer );
- }
- }
- $status = fclose ( $handle );
- if ($retbytes && $status) {
- return $cnt; // return num. bytes delivered like readfile() does.
- }
- return $status;
- }
- ?>
Copy code
Call example:
-
- //Safe download of large files
- download($url, $filename);
Copy code
|