gpt4 book ai didi

php - curl 获取远程文件并同时强制下载

转载 作者:可可西里 更新时间:2023-11-01 13:18:10 27 4
gpt4 key购买 nike

我正在尝试获取远程文件并同时强制将其下载给用户。我无法粘贴代码,代码太长了。但是 curl 函数有效,但问题是它在首先获取远程文件然后强制将其下载给用户之前不会输出任何内容。

我用它来告诉 curl 返回回调

curl_setopt($ch, CURLOPT_READFUNCTION, 'readCallback');

现在在我的 readCallback 函数中我这样做了:

function readCallback($curl, $stream, $maxRead){
$read = fgets($stream, $maxRead);
echo $read;
return $read;
}

但它不会返回任何内容,它只是等待获取远程文件完成。

最佳答案

试试这个,它将使用 curl 获取文件的总大小,然后下载文件的部分块代理它给用户,因为没有 wait curl 首先下载它,我用 avi、mp4、mp3 和 exe 对此进行了测试,希望对您有所帮助:

<?php
$file = 'http://example.com/somefile.mp3';
download($file,2000);

/*
Set Headers
Get total size of file
Then loop through the total size incrementing a chunck size
*/
function download($file,$chunks){
set_time_limit(0);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-disposition: attachment; filename='.basename($file));
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
header('Pragma: public');
$size = get_size($file);
header('Content-Length: '.$size);

$i = 0;
while($i<=$size){
//Output the chunk
get_chunk($file,(($i==0)?$i:$i+1),((($i+$chunks)>$size)?$size:$i+$chunks));
$i = ($i+$chunks);
}

}

//Callback function for CURLOPT_WRITEFUNCTION, This is what prints the chunk
function chunk($ch, $str) {
print($str);
return strlen($str);
}

//Function to get a range of bytes from the remote file
function get_chunk($file,$start,$end){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $file);
curl_setopt($ch, CURLOPT_RANGE, $start.'-'.$end);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'chunk');
$result = curl_exec($ch);
curl_close($ch);
}

//Get total size of file
function get_size($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
return intval($size);
}
?>

关于php - curl 获取远程文件并同时强制下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10991443/

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