通過函數完成下載文件的PHP功能代碼
function download($url, $filename) { // 獲得文件大小, 防止超過2G的文件, 用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' )) { // 當有偏移量的時候,采用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" . "\n\n" ); else { header ( "Content-Length:" . $filesize . "\n\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;}
輸入2個參數即可完成下載 download($url, $filename)
以上所述是小編給大家介紹的PHP下載文件的函數實例代碼的相關知識,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對網站的支持!