PHP使用range協議實現輸出檔案斷點續傳代碼執行個體_PHP教程

來源:互聯網
上載者:User
range協議用途:一般是用在斷點續傳的時候,但是實際的使用者很大,例如你的web server需要輸出一個大檔案,那麼用range可以分段輸出,緩解壓力。同時在提供音樂視頻等服務時可以緩衝下載,如果使用者中途關閉,可以節約網路頻寬。

<?php// 檔案名稱$filename = $_GET ['filename'];// 檔案路徑$location = 'media/' . $filename;// 尾碼$extension = substr ( strrchr ( $filename, '.' ), 1 );if ($extension == "mp3") {$mimeType = "audio/mpeg";} else if ($extension == "ogg") {$mimeType = "audio/ogg";}if (! file_exists ( $location )) {header ( "HTTP/1.1 404 Not Found" );return;}$size = filesize ( $location );$time = date ( 'r', filemtime ( $location ) );$fm = @fopen ( $location, 'rb' );if (! $fm) {header ( "HTTP/1.1 505 Internal server error" );return;}$begin = 0;$end = $size - 1;if (isset ( $_SERVER ['HTTP_RANGE'] )) {if (preg_match ( '/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER ['HTTP_RANGE'], $matches )) {// 讀取檔案,起始節點$begin = intval ( $matches [1] );// 讀取檔案,結束節點if (! empty ( $matches [2] )) {$end = intval ( $matches [2] );}}}if (isset ( $_SERVER ['HTTP_RANGE'] )) {header ( 'HTTP/1.1 206 Partial Content' );} else {header ( 'HTTP/1.1 200 OK' );}header ( "Content-Type: $mimeType" );header ( 'Cache-Control: public, must-revalidate, max-age=0' );header ( 'Pragma: no-cache' );header ( 'Accept-Ranges: bytes' );header ( 'Content-Length:' . (($end - $begin) + 1) );if (isset ( $_SERVER ['HTTP_RANGE'] )) {header ( "Content-Range: bytes $begin-$end/$size" );}header ( "Content-Disposition: inline; filename=$filename" );header ( "Content-Transfer-Encoding: binary" );header ( "Last-Modified: $time" );$cur = $begin;// 定位指標fseek ( $fm, $begin, 0 );while ( ! feof ( $fm ) && $cur <= $end && (connection_status () == 0) ) {print fread ( $fm, min ( 1024 * 16, ($end - $cur) + 1 ) );$cur += 1024 * 16;}

range協議官方文檔:http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

http://www.bkjia.com/PHPjc/824622.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/824622.htmlTechArticlerange協議用途: 一般是用在斷點續傳的時候,但是實際的使用者很大,例如你的web server需要輸出一個大檔案,那麼用range可以分段輸出,緩解...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.