/**
* @param string $url 要需下载的文件地址
* @param string $save_dir 保存目录
* @param string $filename 保存文件名
* @param int $type 下载类型
* @return array|bool
* 下载远程文件
*/
function DownloadFile($url, $save_dir = '', $filename = '', $type = 0) {
$ext = array('gif','jpg','jpeg','bmp','png','webp');
if (trim($url) == '') {
return false;
}
if (trim($save_dir) == '') {
$save_dir = './';
}
if (0 !== strrpos($save_dir, '/')) {
$save_dir.= '/';
}
//创建保存目录
if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {
return false;
}
//获取远程文件所采用的方法
if ($type) {
$ch = curl_init();
$timeout = 100;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 跟随重定向
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 禁用SSL证书验证
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$content = curl_exec($ch);
curl_close($ch);
} else {
ob_start();
readfile($url);
$content = ob_get_contents();
ob_end_clean();
}
$size = strlen($content);
//文件大小
$info = pathinfo($url);
$weurl = parse_url($url);
if(isset($weurl['host']) && $weurl['host'] == 'mmbiz.qpic.cn'){
if(isset($weurl['query'])){
$exp = explode('=',$weurl['query']);
}else{
$exp = ['wx','jpg'];
}
$info['extension'] = $exp[1];
$info['basename'] = 'WeChat_'.time().'.'.$info['extension'];
}
if(isset($info['extension']) && in_array($info['extension'],$ext)){
if($filename){
$fiex = '.'.$info['extension'];
$fp2 = @fopen($save_dir . $filename.$fiex, 'a');
$newname = $filename.$fiex;
}else{
$fp2 = @fopen($save_dir . $info['basename'], 'a');
$newname = $info['basename'];
}
fwrite($fp2, $content);
fclose($fp2);
unset($content, $url);
return array(
'file_name' => $newname,
'save_path' => '/'.$save_dir . $newname
);
}else{
return array(
'file_name' => $url,
'save_path' => $url
);
}
}
发表评论