zoukankan      html  css  js  c++  java
  • 关于远程操作的函数

    /**
    * Enhanced file_get_contents, use curl to fetch remote file
    * @param $file
    * @author Wilson Zeng
    */
    function ex_file_get_contents($file){
    //if is url?
    if(preg_match('/^[a-zA-z]+:\/\/[^\s]*/i', $file)){//a url
    $ch = curl_init($file);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $rs = curl_exec($ch);
    curl_close($ch);
    return $rs;
    }else{
    return file_get_contents($file);
    }
    }

    /**
    * Enhanced copying file, can copy remote file(use curl)
    * @param $url
    * @param $destpath
    * @author Wilson Zeng
    */
    function trans_file($url, $destpath){
    if(preg_match('/^[a-zA-z]+:\/\/[^\s]*/i', $url)){//a url
    $ch = curl_init($url);
    $opts = array(
    CURLOPT_RETURNTRANSFER => 1,
    );
    curl_setopt_array($ch, $opts);
    $file_str = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if($http_code < 200 || $http_code >= 300 || file_put_contents($destpath, $file_str) <= 0){
    return FALSE;
    }
    }else{//a local file
    return copy($url, $destpath);
    }
    return TRUE;
    }

    /**
    * POST/GET remote url
    * @author Wilson Zeng
    * @param $url
    * @param $timeout [optinal]
    * @param $post_data [optional]
    * @param $http_code [optional] return http code
    * @return RESPONSE
    */
    function get_remote_file($url, $timeout = 0, $post_data = NULL, &$http_code = NULL, &$curl_errno = NULL, &$curl_error = NULL){
    $ch = curl_init($url);
    $opts[CURLOPT_RETURNTRANSFER] = 1;
    if($post_data){
    $opts[CURLOPT_POST] = 1;
    if(is_array($post_data)){
    $opts[CURLOPT_POSTFIELDS] = http_build_query($post_data);
    }elseif(is_string($post_data)){
    $opts[CURLOPT_POSTFIELDS] = $post_data;
    }
    }
    if($timeout > 0){
    $opts[CURLOPT_TIMEOUT] = $timeout;
    }
    curl_setopt_array($ch, $opts);
    $rs = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_errno = curl_errno($ch);
    $curl_error = curl_error($ch);
    curl_close($ch);
    return $rs;
    }
  • 相关阅读:
    Spring事件机制
    设计模式(07)——设计原则(2)
    设计模式(06)——设计原则(1)
    使用Feign发送HTTP请求
    设计模式(05)——组合和继承
    设计模式(04):接口和抽象类
    设计模式(03):面向对象与面向过程的区别与联系
    设计模式(二):面向对象及其特性分析
    设计模式(一):学习大纲
    Java8日期时间——LocalDateTime的使用以及相互转换
  • 原文地址:https://www.cnblogs.com/ppoo24/p/2324535.html
Copyright © 2011-2022 走看看