zoukankan      html  css  js  c++  java
  • PHP文件下载

    $images = [
        'http://www.thinkphp.cn/Uploads/editor/2017-11-02/59fac47ed670b.png',
        'http://www.thinkphp.cn/Uploads/editor/2017-11-02/59fac48995e58.png'
    ];
    
    function download($url, $path = 'd:/images/'){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        $filename = pathinfo($url, PATHINFO_BASENAME);
        $resource = fopen($path . $filename, 'a');
        fwrite($resource, $file);
        fclose($resource);
    }
    
    foreach ( $images as $url ) {
        //var_dump($url);exit();
        download($url);
    }

    封装一个类

    class Spider {
     
      public function downloadImage($url, $path = 'd:/images/')
      {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        $filename = pathinfo($url, PATHINFO_BASENAME);
        $resource = fopen($path . $filename, 'a');
        fwrite($resource, $file);
        fclose($resource);
      }
    }  

    封装成类之后,我们可以这样调用

    $spider = new Spider();
     
    foreach ( $images as $url ) {
      $spider->downloadImage($url);
    }

     链接为302的情况

    $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            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; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0');
            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);
            $headers = curl_getinfo($ch);
    
  • 相关阅读:
    HDU 4539郑厂长系列故事――排兵布阵(状压DP)
    HDU 2196Computer(树形DP)
    HDU 4284Travel(状压DP)
    HDU 1520Anniversary party(树型DP)
    HDU 3920Clear All of Them I(状压DP)
    HDU 3853LOOPS(简单概率DP)
    UVA 11983 Weird Advertisement(线段树求矩形并的面积)
    POJ 2886Who Gets the Most Candies?(线段树)
    POJ 2828Buy Tickets
    HDU 1394Minimum Inversion Number(线段树)
  • 原文地址:https://www.cnblogs.com/pcx105/p/8358357.html
Copyright © 2011-2022 走看看