PHP下载文件的函数实例代码
程序员文章站
2024-02-14 12:55:46
通过函数完成下载文件的php功能代码
function download($url, $filename) {
// 获得文件大小, 防止超过2g的文件, 用...
通过函数完成下载文件的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下载文件的函数实例代码的相关知识,希望对大家有所帮助