php 按远程图片路径下载存储本地

180it 2021-10-15 PM 869℃ 0条
 用法:downpic($url,'/www/wwwroot/www.xxx123.com/');



    //下载远程图片
     
      function downpic($url,$path){
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            $header = array();
            $header[] = 'Host: t.xx.com';
            $header[] = 'Accept-Encoding: gzip, deflate, sdch';
            $header[] = 'Accept-Language: zh-CN,zh;q=0.8';
            $header[] = 'Cookie: _hc.v=d846d370-b934-97da-2584-df1d51be8040.1476003831; aburl=1; cy=2; cye=beijing; _tr.u=rw0PincYp5DQrbEl; t_rct=20921750; PHOENIX_ID=0a010818-158198588e7-de0339';
            $header[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8';
            $header[] = 'Connection: keep-alive';
    //        $header[] = 'X-UCBrowser-UA: dv(HUAWEI G610-T00);pr(UCBrowser/10.4.0.558);ov(Android 4.2.1);ss(360*640);pi(540*960);bt(UC);pm(1);bv(1);nm(0);im(0);sr(0);nt(2);';
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            //若给定url自动跳转到新的url,有了下面参数可自动获取新url内容:302跳转
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            //设置cURL允许执行的最长秒数。
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36');
            curl_setopt($ch, CURLOPT_REFERER, $url);
            curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
            $content = curl_exec($ch);
            //获取请求返回码,请求成功返回200
            $code = curl_getinfo($ch,CURLINFO_HTTP_CODE);        
            //获取一个cURL连接资源句柄的信息。
            //$headers 中包含跳转的url路径 
    //        $headers = curl_getinfo($ch);
      $filename = pathinfo($url, PATHINFO_BASENAME);
      
      
    $mDir=geturlPath($url,"https://www.xxx.com/");  //为远程链接 https://www.xxx.com/ 
    makeDirByPath($mDir); //创建路径
    
    
      $resource = fopen($mDir . $filename, 'a');
      fwrite($resource, $content);
      fclose($resource);
      
         //   return $content;
        }
        
        
        
        
        
    function geturlPath($url,$wwwurl){
    $makeDir= str_replace($wwwurl,"",$url);
    $netfilename=basename($makeDir);
    //echo $netfilename.'<br/>';
    $mDir= str_replace($netfilename,"",$makeDir);
    return $mDir;
    }
    
    
    
    /**
     * 根绝文件路径创建对应的目录
     * 
     * @param string $path  a/b/c/d/
     * 
     */
    function makeDirByPath($path){
        if(!file_exists($path)){
            makeDirByPath(dirname($path));
            mkdir($path, 0777);
        }
    }

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

php 按远程图片路径下载存储本地