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);
    
  • 相关阅读:
    利用Flot作基于时间段的曲线图
    Linux Apache使用CGI
    Windows node.js安装运行npm显示类似"ENOENT, stat 'C:UsersXXXXAppDataRoaming pm'错误
    JavaWeb返回Json格式数据JQuery Ajax无法解析的问题
    C++ 14 auto
    [原创] Jenkins slave agent 分布式构建
    [原创] Jenkins 邮件配置 (使用 Jenkins Email Extension Plugin)
    Linux 域名服务器配置
    证书管理
    Ubuntu 安装 Kubernetes
  • 原文地址:https://www.cnblogs.com/pcx105/p/8358357.html
Copyright © 2011-2022 走看看