如何在PHP中封装一个请求类

发布时间:2021-06-07 17:05:34 作者:Leah
来源:亿速云 阅读:127

这篇文章给大家介绍如何在PHP中封装一个请求类,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

1.源码

<?php
namespace app\common\components;
use Yii;
use app\common\services\BaseService;
class HttpClient extends BaseService{
  private static $headers = [];
  private static $cookie = null;
  public static function get($url, $param =[]) {
    return self::curl($url, $param,"get");
  }
  public static function post($url, $param,$extra = [] ) {
    return self::curl($url, $param,"post");
  }
  protected static function curl($url, $param, $method = 'post')
  {
    $calculate_time1 = microtime(true);
    // 初始华
    $curl = curl_init();
    // 设置url
    curl_setopt($curl, CURLOPT_URL, $url);
    // 设置为0表示不返回HTTP头部信息
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // 设置为1返回将curl_exec()获取的信息以字符串返回,而不是直接输出 设置为0返回true/false
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    // TRUE 将在安全传输时输出 SSL 证书信息到 STDERR。
    curl_setopt($curl, CURLOPT_CERTINFO , true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    // FALSE 禁止 cURL 验证对等证书
    // 交换证书可以在 CURLOPT_CAINFO 选项中设置,CURLOPT_CAPATH中设置证书目录。
      curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
      if( isset( Yii::$app->params['curl'] ) && isset(Yii::$app->params['curl']['timeout']) ){
      curl_setopt($curl, CURLOPT_TIMEOUT, Yii::$app->params['curl']['timeout']);
    }else{
      curl_setopt($curl, CURLOPT_TIMEOUT, 5);
    }
    // array_key_exists — 检查数组里是否有指定的键名或索引
      // CURLOPT_USERAGENT在HTTP请求中包含一个"User-Agent: "头的字符串
    if(array_key_exists("HTTP_USER_AGENT",$_SERVER)){
      curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    }
    // CURLOPT_HTTPHEADER设置 HTTP 头字段的数组。格式: array('Content-type: text/plain', 'Content-length: 100')
    if(!empty(self::$headers)){
      $headerArr = [];
      foreach( self::$headers as $n => $v ) {
        $headerArr[] = $n .': ' . $v;
      }
      curl_setopt ($curl, CURLOPT_HTTPHEADER , $headerArr ); //构造IP
    }
    // CURLOPT_COOKIE设定 HTTP 请求中"Cookie: "部分的内容。多个 cookie 用分号分隔,分号后带一个空格(例如, "fruit=apple; colour=red")。
    if( self::$cookie ){
      curl_setopt($curl, CURLOPT_COOKIE, self::$cookie);
    }
    // post处理 :TRUE 时会发送 POST 请求,类型为:application/x-www-form-urlencoded,是 HTML 表单提交时最常见的一种。
    if ($method == 'post')
    {
      curl_setopt($curl, CURLOPT_POST, TRUE);
      // 如果为数组就变成字符串
      if(is_array($param)){
        $param = http_build_query($param);
      }
      // 全部数据使用HTTP协议中的 "POST" 操作来发送。 要发送文件,在文件名前面加上@前缀并使用完整路径。
      curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
    }else{
      //get请求
      curl_setopt($curl, CURLOPT_POST, FALSE);
    }
    // 执行输出
    $info = curl_exec($curl);
    //log:返回最后一次的错误代码
    $_errno = curl_errno($curl);
    $_error = '';
    if($_errno)
    {
      // 返回当前会话最后一次错误的字符串
      $_error = curl_error($curl);
    }
    curl_close($curl);
    // 花费的时间
    $calculate_time_span = microtime(true) - $calculate_time1;
    $log = \Yii::$app->getRuntimePath().DIRECTORY_SEPARATOR.'curl.log';
    // int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )
    file_put_contents($log,date('Y-m-d H:i:s')." [ time:{$calculate_time_span} ] url: {$url} \nmethod: {$method} \ndata: ".json_encode($param)." \nresult: {$info} \nerrorno: {$_errno} error: {$_error} \n",FILE_APPEND);
    if( $_error ){
      return self::_err( $_error );
    }
    return $info;
  }
  public static function setHeader($header){
     self::$headers = $header;
  }
  public static function setCookie( $cookie ){
    self::$cookie = $cookie;
  }
}

关于如何在PHP中封装一个请求类就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. Jackson的JSON工具类如封装 JsonUtils用法
  2. 使用PHP怎么封装一个MongoDB连接类

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php

上一篇:使用thinkPHP怎么实现事务操作

下一篇:怎么在tp5中利用递归实现无限级分类

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》