我有这个代码,我有一个远程文件列表(例如图像),可以使用多卷曲下载:
$urls = array('http://www.google.com/images/nav_logo82.png', 'http://static.php.net/www.php.net/images/php.gif');
function curl_progress_callback($a=0,$b=0,$c=0, $d=0) {
/* ?? */
}
$save_to='./public/images/';
$conn = array();
$fp = array();
$mh = curl_multi_init();
foreach ($urls as $i => $url) {
$g=$save_to.basename($url);
if(!is_file($g)){
$conn[$i]=curl_init($url);
$fp[$i]=fopen ($g, "wb");
curl_setopt ($conn[$i], CURLOPT_FILE, $fp[$i]);
curl_setopt ($conn[$i], CURLOPT_HEADER ,0);
curl_setopt($conn[$i],CURLOPT_CONNECTTIMEOUT,60);
curl_setopt ($conn[$i], CURLOPT_MAXCONNECTS, 10);
curl_setopt($conn[$i], CURLOPT_NOPROGRESS, false);
curl_setopt($conn[$i], CURLOPT_PROGRESSFUNCTION, 'curl_progress_callback');
curl_multi_add_handle ($mh,$conn[$i]);
}
}
do {
$n=curl_multi_exec($mh,$active);
}
while ($active);
foreach ($urls as $i => $url) {
curl_multi_remove_handle($mh,$conn[$i]);
curl_close($conn[$i]);
fclose($fp[$i]);
}
curl_multi_close($mh);
问题是我想制作某种进度条,所以php应该给我关于下载进度的信息。例如,我希望每次文件下载完成时都有一个计数器增加一个(然后在.txt文件上写这个计数器并用ajax每n秒检索一次很容易,知道有多少个文件已经下载到那一刻)。为此,我附加了函数“curl_progress_callback”,但我不知道该把它放在里面做我想要的......
编辑:最后我设法通过一个小功能来实现这个目标
function define_progress_callback($i) {
global $conn;
$flag = 1;
curl_setopt($conn[$i], CURLOPT_PROGRESSFUNCTION, function ($a=0,$b=0,$c=0,$d=0) use($i, &$flag) {
if($b != 0 && $flag != 0 && $b/$a == 1) {
/* Put here the code to execute every time that a download finishes */
$flag = 0;
}
});
}
$save_to='./public/images/';
$conn = array();
$fp = array();
$mh = curl_multi_init();
foreach ($urls as $i => $url) {
$g=$save_to.basename($url);
$conn[$i]=curl_init($url);
$fp[$i]=fopen ($g, "wb");
curl_setopt ($conn[$i], CURLOPT_FILE, $fp[$i]);
curl_setopt ($conn[$i], CURLOPT_HEADER ,0);
curl_setopt($conn[$i],CURLOPT_CONNECTTIMEOUT,60);
curl_setopt ($conn[$i], CURLOPT_MAXCONNECTS, 10);
curl_setopt($conn[$i], CURLOPT_NOPROGRESS, false);
define_progress_callback($i);
curl_multi_add_handle ($mh,$conn[$i]);
}
do {
$n=curl_multi_exec($mh,$active);
}
while ($active);
foreach ($urls as $i => $url) {
curl_multi_remove_handle($mh,$conn[$i]);
curl_close($conn[$i]);
fclose($fp[$i]);
}
curl_multi_close($mh);
但是,如果有人知道更好的解决方案,我将不胜感激......