Php security code for downloading large files
- /**
- * Secure 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 );
- ?>
The above code exceeded php in the case of large files. when the file with the maximum memory configured by ini is used, the server will occupy a lot of CPU resources. files cannot be downloaded normally, and only dozens of Kb of files can be downloaded. You can use the following code to solve the problem:
- /**
- * Implementation code for secure download of large files
- * Edit bbs.it-home.org
- */
- Function download ($ url, $ filename ){
- // Obtain the file size to prevent files exceeding 2 GB from being read by sprintf.
- $ Filesize = sprintf ("% u", filesize ($ url ));
- If (! $ Filesize ){
- Return;
- }
- Header ("Content-type: application/octet-stream \ n"); // 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 206 breakpoint resume header.
- $ 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". "\ n ");
- } Else {
- Header ("Content-Length:". $ filesize. "\ n ");
- $ 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;
- }
- ?>
Call example:
- // Secure download of large files
- Download ($ url, $ filename );
|