-
<html>
-
<head>
-
<title>show curl download progress</title>
-
-
<style type="text/css">
-
#progress-bar {
-
width: 200px;
-
padding: 2px;
-
border: 2px solid #aaa;
-
background: #666666;
-
}
-
-
#progress {
-
background: #fff;
-
color: #fff000;
-
white-space: nowrap;
-
padding: 5px 0;
-
text-indent: 5px;
-
width: 0;
-
}
-
</style>
-
<script type="text/javascript">
-
function updateProgress(percentage) {
-
var progressElement = document.getElementById_x('progress')
-
progressElement.style.width = Math.round(percentage*200)+"px";
-
progressElement.innerHTML = Math.round(percentage*100) + '%';
-
}
-
</script>
-
</head>
-
<body>
-
<div id="progress-bar">
-
<div id="progress">0%</div>
-
</div>
-
<?php
-
//需要下载的远程文件url
-
$url="没那么简单.mp3?xcode=31a91a4398f5608cf126db69f9daa1ec&mid=0.44357582289098";
-
-
$ch=curl_init();//Initialize a cURL session.
-
-
$fp = fopen("/var/www/target.mp3",'w');
-
-
$a_opt=array(
-
CURLOPT_URL => $url,
-
CURLOPT_HEADER => 0,//不包含头信息到输出文件target.mp3
-
CURLOPT_RETURNTRANSFER => 1,//当CURLOPT_RETURNTRANSFER设置为false时,方法curl_exec的调用在成功时会直接输出结果并返回bool(true),而不是以字符串形式返回取得的结果数据.
-
CURLOPT_NOPROGRESS => 0,//true用来禁用curl transfers的进度条显示,注意:php默认设置该选项为true,此处我们需要false
-
CURLOPT_PROGRESSFUNCTION => 'progress',//用来显示进度的回调函数
-
CURLOPT_FILE => $fp, //目标文件保存路径
-
CURLOPT_FOLLOWLOCATION => TRUE,
-
CURLOPT_BUFFERSIZE => 64000,
-
);
-
curl_setopt_array($ch,$a_opt);
-
-
//echo "dltotal, dlnow, percent, now, ultotal, ulnow"."
";
-
-
$str=curl_exec($ch);
-
-
curl_close($ch);
-
-
//$dltotal:download total 下载文件总大小
-
//$dlnow:download now 当前已经下载大小
-
//$ultotal:upload total 上传文件总大小
-
//$ulnow:upload now 当前已经上传大小
-
function progress($dltotal,$dlnow,$ultotal, $ulnow){
-
$now = date('Y-m-d H:i:s');//当前时间
-
//刚开始下载或上传时,$dltotal和$ultotal为0,此处避免除0错误
-
if(empty($dltotal)){
-
$percent = "0";
-
}else{
-
$percent = $dlnow/$dltotal;
-
}
-
//echo "$dltotal, $dlnow, $percent, $now , $ultotal, $ulnow"."
";
-
echo "";
-
ob_flush();
-
flush();
-
return(0);
-
}
-
-
?>
-
</body>
-
</html>
调试方法:将$url改为真正可用url(比如打开百度mp3播放器,复制下载地址),新建以上php文件保存到apache根目录下,从浏览器访问即可
阅读(5352) | 评论(0) | 转发(0) |