php下载网络图片到本地|完整代码

<?php
	/**
  * 下载图片到服务器
  * @param string $webImgUrl 图片路径
  * @param string $fileName 要保存的文件名
  */

	$fileName=date("Y-m-d")."-".time().rand(1,1000);
	$webImgUrl="https://eyunzhu.com/wp-content/uploads/2018/06/logo2.png";
	
	echo DownLoadPic($webImgUrl,$fileName);

     function DownLoadPic($webImgUrl,$fileName){
        if($webImgUrl == ""){
            return false;
        }
        $filePath = "/upload/video_img/";
        $filename = $fileName.'.jpg';
        // 检查路径是否存在,如不存在则创建
        $dir = '.'.$filePath;
        if (!is_dir($dir)){
            //第三个参数是“true”表示能创建多级目录,iconv防止中文目录乱码
            $res=mkdir(iconv("UTF-8", "GBK", $dir),0777,true);
        }
        ob_start();
        readfile($webImgUrl);
        $img=ob_get_contents();
        ob_end_clean();
        $size=strlen($img);
        $fp2=fopen('.'.$filePath.$filename,"a");
        if(fwrite($fp2,$img) === false){
            $this->ErrorLogger('dolwload image falied. Error Info: 无法写入图片'.date('Y-m-d H:i:s'));
            exit();
        }
        fclose($fp2);
        return $filePath.$filename;
    }

 	function ErrorLogger($errMsg){
        $logger = fopen('./ErrorLog.txt', 'a+');
        fwrite($logger, date('Y-m-d H:i:s')." Error Info : ".$errMsg."\r\n");
    }
    

?>
云竹互联
admin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: