如何通过PHP脚本下载大文件?
要通过PHP脚本下载大文件,代码如下-
示例
<?php
function readfile_chunked($filename,$retbytes=true) {
$chunksize = 1*(1024*1024); // how many bytes per chunk the user wishes to read
$buffer = '';
$cnt =0;
$handle = fopen($filename, 'rb');
if ($handle === false) {
return false;
}
while (!feof($handle)) {
$buffer = fread($handle, $chunksize);
echo $buffer;
if ($retbytes) {
$cnt += strlen($buffer);
}
}
$status = fclose($handle);
if ($retbytes && $status) {
return $cnt; // return number of bytes delivered like readfile() does.
}
return $status;
}
?>输出结果
这将产生以下输出-
The large file will be downloaded.
函数“readfile_chunked”(用户定义)具有两个参数:文件名和返回字节数的默认值“true”,表示已成功下载大文件。声明了变量“chunksize”,其中每个块需要读取的字节数。将'buffer'变量分配为null,将'cnt'设置为0。以二进制读取模式打开文件,并将其分配给变量'handle'。
在到达“handle”文件的末尾之前,while循环将运行并根据需要读取的块数读取文件的内容。接下来,它显示在屏幕上。如果'retbytes'(函数的第二个参数)的值为true,则将缓冲区的长度添加到'cnt'变量中。否则,将关闭文件并返回“cnt”值。最后,该函数返回“状态”。