Last active
November 24, 2016 00:33
-
-
Save fasthold/f57af79370ca0547932d to your computer and use it in GitHub Desktop.
PHP使用curl下载文件时输出下载进度
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// 现在输出是没问题了,但是实际保存为文件还有问题 | |
// from: http://stackoverflow.com/questions/13958303/curl-download-progress-in-php | |
// 原文中的代码有bug,作了修改 | |
$url = 'http://ipv4.speedtest-sgp1.digitalocean.com/10mb.test'; | |
echo "<pre>"; | |
echo "Loading ..."; | |
ob_flush(); | |
flush(); | |
downloadFileWithCURL($url, './10mb.test'); | |
echo "Done"; | |
ob_flush(); | |
flush(); | |
function downloadFileWithCURL($url, $localFilePath) { | |
function progressCallback($resource, $download_size = 0, $downloaded = 0, $upload_size = 0, $uploaded = 0) { | |
/** | |
* $resource parameter was added in version 5.5.0 breaking backwards compatibility; | |
* if we are using PHP version lower than 5.5.0, we need to shift the arguments | |
* @see http://php.net/manual/en/function.curl-setopt.php#refsect1-function.curl-setopt-changelog | |
*/ | |
if (version_compare(PHP_VERSION, '5.5.0') < 0) { | |
$uploaded = $upload_size; | |
$upload_size = $downloaded; | |
$downloaded = $download_size; | |
$download_size = $resource; | |
} | |
// Handle progress | |
if ($download_size > 0) echo round($downloaded / $download_size * 100, 2) . "\n"; | |
ob_flush(); | |
flush(); | |
sleep(1); | |
// just to see effect | |
} | |
$fp = fopen($localFilePath, 'w+'); | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $url); | |
curl_setopt($ch, CURLOPT_FILE, $fp); | |
//curl_setopt($ch, CURLOPT_BUFFERSIZE,128); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'progressCallback'); | |
curl_setopt($ch, CURLOPT_NOPROGRESS, false); | |
// needed to make progress function work | |
curl_setopt($ch, CURLOPT_HEADER, 0); | |
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); | |
curl_exec($ch); | |
curl_close($ch); | |
fclose($fp); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment