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);
    
  • 相关阅读:
    js中split字符串分割
    获取日期,实时显示当前时间,时间相减
    5.5.4 函数内部属性
    单选按钮radio和下拉选择select,ajax返回数据回显对应值
    如何在HTML不同的页面中,共用头部与尾部?
    android-Activity(四大组件之一)
    android-ImageView及其子类
    android-ActionBar
    android- 菜单
    android-Fragment
  • 原文地址:https://www.cnblogs.com/pcx105/p/8358357.html
Copyright © 2011-2022 走看看