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);
    
  • 相关阅读:
    docker运行jar包
    jQuery动态添加元素并绑定事件
    Ubuntu将软件(Sublime Text 2为例)锁定到启动器
    jQuery实现列表自动滚动
    浅谈css中的position属性
    关于jQuery中.attr()和.prop()的问题
    Python_opencv库
    Python_faker (伪装者)创建假数据
    Python_Tips_dumpload 和 dumpsloads 的区别与联系
    Linux_CentOS 7下Nginx服务器的安装配置
  • 原文地址:https://www.cnblogs.com/pcx105/p/8358357.html
Copyright © 2011-2022 走看看