如何通过PHP脚本下载大文件?
phpserver side programmingprogramming更新于 2025/4/16 20:07:17
通过PHP脚本下载大文件,代码如下−
示例
<?php function readfile_chunked($filename,$retbytes=true) { $chunksize = 1*(1024*1024); // 用户希望读取每个块多少字节 $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; // 返回已传送的字节数,就像 readfile() 一样。 } return $status; } ?>
输出
这将产生以下输出 −
The large file will be downloaded.
函数 ‘readfile_chunked’(用户定义)接受两个参数 - 文件名和返回的字节数的默认值 ‘true’,表示已成功下载大文件。变量 ‘chunksize’ 已声明为需要读取的每个块的字节数。‘buffer’ 变量被赋值为 null,‘cnt’ 设置为 0。文件以二进制读取模式打开并赋值给变量 ‘handle’。
直到到达 ‘handle’ 的文件末尾,while 循环运行并根据需要读取的块数读取文件的内容。接下来,它将显示在屏幕上。如果 ‘retbytes’ 的值(函数的第二个参数)为真,则将缓冲区的长度添加到‘cnt’变量中。否则,关闭文件并返回‘cnt’值。最后,该函数返回‘status’。