编程爱好者之家
最近用到了下载远程图片的功能,于是就写了个小结,希望对大家有帮助,代码如下
function getImage($url,$save_dir='Public/upload/downpic/',$filename='',$type=1){ $url = str_replace('https://','http://',$url); if(!isset(parse_url($url)['host']) || strstr(strtolower(parse_url($url)['host']),'anruan.com')){ return $url; } $filename = trim($filename); if(trim($filename)==''){//保存文件名 $filename = basename($url); $filename = trim($filename); $houzuiA = pathinfo($filename); if(!isset($houzuiA['extension']) || empty($houzuiA['extension'])){ $filename = time().rand(100,999).'.jpg'; }else{ $filename = time().rand(100,999).'.'.$houzuiA['extension']; } } //创建保存目录 $save_dir = $save_dir.date('Ymd').'/'; if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){ return $url; } //获取远程文件所采用的方法 if($type){ $ch=curl_init(); $timeout=5; curl_setopt($ch,CURLOPT_URL,$url); curl_setopt ($ch, CURLOPT_REFERER, 'http://'.parse_url($url)['host']);//这里为空也行,为他的主域名也可 curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); $img=curl_exec($ch); curl_close($ch); }else{ ob_start(); readfile($url); $img=ob_get_contents(); ob_end_clean(); } //文件大小 if(($fp2=@fopen(trim($save_dir.$filename),'a')) !== false){ fwrite($fp2, $img); fclose($fp2); } unset($img,$url); //返回绝对路径 return C('INDEX_CENTER_URL').$save_dir.$filename; }