设为首页 加入收藏

TOP

php使用curl下载指定大小的文件(二)
2017-10-16 18:19:10 】 浏览:6854
Tags:php 使用 curl 下载 指定 大小 文件
lfInstanceList
[$pid])){ self::$selfInstanceList[$pid] = new self($pid); } return self::$selfInstanceList[$pid]; } private function __construct($pid) { $this->pid = $pid; $this->downloadedFileSize = 0; $this->fileFullName = ''; $this->hasOverMaxSize = false; $this->downloadData = ''; } /** * 保存文件 */ public function saveMaxSizeData2File(){ if(empty($resp_data)){ $resp_data = $this->downloadData; } $fileFullName = '/tmp/http_'.$this->pid.'_'.time()."_{$this->maxSize}.download"; if($resp_data && strlen($resp_data)>0) { list($headerOnly, $bodyOnly) = explode("\r\n\r\n", $resp_data, 2); $saveDataLenth = ($this->downloadedFileSize < $this->maxSize) ? $this->downloadedFileSize : $this->maxSize; $needSaveData = substr($bodyOnly, 0, $saveDataLenth); if(empty($needSaveData)){ return; } file_put_contents($fileFullName, $needSaveData); if(file_exists($fileFullName)){ $this->fileFullName = $fileFullName; } } } /** * 返回文件的md5 * @return string */ public function returnFileMd5(){ $md5 = ''; if(file_exists($this->fileFullName)){ $md5 = md5_file($this->fileFullName); } return $md5; } /** * 返回已下载的size * @return int */ public function returnSize(){ return ($this->downloadedFileSize < $this->maxSize) ? $this->downloadedFileSize : $this->maxSize; } /** * 删除下载的文件 */ public function deleteFile(){ if(file_exists($this->fileFullName)){ unlink($this->fileFullName); } } }

 

 

    curl请求的代码实例中,实现限制下载大小

……
curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'on_curl_write');//设置回调函数
……
$pid = getmypid();
$downloadSizeRecorder = DownloadSizeRecorder::getInstance($pid);
$downloadSizeRecorder->maxSize = $size_limit;
……
//发起curl请求
$response = curl_exec($ch);
……
//保存文件,返回md5
$downloadSizeRecorder->saveMaxSizeData2File();  //保存
$downloadFileMd5 = $downloadSizeRecorder->returnFileMd5();
$downloadedfile_size = $downloadSizeRecorder->returnSize();
$downloadSizeRecorder->deleteFile();

 

     到这里,踩了一个坑。增加了on_curl_write后,$response会返回true,导致后面取返回内容的时候异常。好在已经实时限制了下载的大小,用downloadData来记录了已经下载的内容,直接可以使用。

if($response === true){
    $response = $downloadSizeRecorder->downloadData;
}

 

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇PHP字符串替换str_replace()函数4.. 下一篇Phpstorm中如何配置svn详细步骤

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目