Php file download function-carlo-jie
PHP code for downloading objects using functions
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;
}
Enter two parameters to complete the download.
download($url, $filename)