gpt4 book ai didi

php - 使用 PHP 流式传输大文件

转载 作者:IT王子 更新时间:2023-10-29 00:52:24 25 4
gpt4 key购买 nike

我有一个 200MB 的文件,我想通过下载将其提供给用户。但是,由于我们希望用户只下载此文件一次,因此我们这样做:

echo file_get_contents('http://some.secret.location.com/secretfolder/the_file.tar.gz');

强制下载。然而,这意味着必须将整个文件加载到内存中,这通常是行不通的。我们如何以每 block 几 kb 的速度将此文件流式传输给他们?

最佳答案

试试这样的(来源 http://teddy.fr/2007/11/28/how-serve-big-files-through-php/):

<?php
define('CHUNK_SIZE', 1024*1024); // Size (in bytes) of tiles chunk

// Read a file and display its content chunk by chunk
function readfile_chunked($filename, $retbytes = TRUE) {
$buffer = '';
$cnt = 0;
$handle = fopen($filename, 'rb');

if ($handle === false) {
return false;
}

while (!feof($handle)) {
$buffer = fread($handle, CHUNK_SIZE);
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;
}

// Here goes your code for checking that the user is logged in
// ...
// ...

if ($logged_in) {
$filename = 'path/to/your/file';
$mimetype = 'mime/type';
header('Content-Type: '.$mimetype );
readfile_chunked($filename);

} else {
echo 'Tabatha says you haven\'t paid.';
}
?>

关于php - 使用 PHP 流式传输大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6914912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com