PHP Curl 封装类 [ [ Curl.class ] ]

CURL SSL 认证问题http://www.3mu.me/php%E7%9A%84curl%E9%80%89%E9%A1%B9curlopt_ssl_verifypeer%E8%AF%A6%E8%A7%A3/

https://www.liangzl.com/get-article-detail-14723.html

https://www.cnblogs.com/zwesy/p/9461833.html

https://max.book118.com/html/2017/1215/144290412.shtm

https://blog.csdn.net/wsmt1121/article/details/78022623

参考开源类:Snoopy.class.php (Snoopy-2.0.0 )

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Class Curl
 */
class Curl
{
	/**** Public variables ****/
	/* user definable vars */
	var $url = "https://localhost/api/machines/";
	var $user = ""; // user for http authentication
	var $pass = ""; // password for http authentication
	var $http_auth = CURLAUTH_ANY;
	var $ssl_verify_peer = FALSE;
	var $ssl_verify_host = FALSE;

	var $port = 80; // port we are connecting to
	var $referer = ""; // referer info to pass
	var $raw_headers = array(); // array of raw headers to send
	var $agent = "";
	// $raw_headers["Content-type"]="text/html";

	// http accept types
	var $accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*";
	var $results = ""; // where the content is put
	var $headers = array(); // headers returned from server sent here
	var $timeout = 30; // timeout on read operations, in seconds
	// send Accept-encoding: gzip?
	var $use_gzip = true;

	/**** Private variables ****/
	private $ch = NULL;
	private $host = "";
	private $_httpmethod = "GET"; // default http request method
	private $_httpversion = "HTTP/1.0"; // default http request version
	private $_mime_boundary = ""; // MIME boundary for multipart/form-data submit type

	/**
	 * Curl constructor.
	 */
	public function __construct()
	{
		$this->ch = curl_init();
		if ($this->ch === FALSE)
			if (!extension_loaded('php_curl')) {
				trigger_error('Curl initialization error, make sure php_curl extension is turned on correctly.', E_USER_ERROR);
				exit;
			}
		$this->init();
	}

	/**
	 * Curl destructor.
	 */
	public function __destruct()
	{
		curl_close($this->ch);
	}

	/**
	 * Curl initialization.
	 */
	public function init()
	{
		if (!isset($this->raw_headers["Content-Type"]))
		{
			$this->raw_headers["Content-Type"]  = "Content-type: text/xml;charset=\"utf-8\"";
		}
		if (!isset($this->raw_headers["Cache-Control"]))
		{
			$this->raw_headers["Cache-Control"] = "No-Cache";
		}
		if (!isset($this->raw_headers["Cache-Control"]))
		{
			$this->raw_headers["Accept"] ="application/json";
		}
	}

	/**
	 * Set Post Request.
	 * @return $this
	 */
	public function post()
	{
		$this->_httpmethod = "POST";
		return $this;
	}

	/**
	 * launch a http request.
	 * @param $method api method
	 * @param array $params
	 * @param string $url
	 * @return $this
	 */
	public function request($method, $params = array(), $url = "")
	{
		$this->url = empty($url) ? $this->url : $url;
		$uri_parts = parse_url($this->url);
		if (!empty($uri_parts["user"]))
			$this->user = $uri_parts["user"];
		if (!empty($uri_parts["pass"]))
			$this->pass = $uri_parts["pass"];
		if (empty($uri_parts["query"]))
			$uri_parts["query"] = '';
		if (empty($uri_parts["path"]))
			$uri_parts["path"] = '';

		switch (strtolower($uri_parts["scheme"])) {
			case "https":
				curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, $this->ssl_verify_peer);
				curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, $this->ssl_verify_host);
				$this->port = 443;
			case "http":
				$this->host = $uri_parts["host"];
				if (!empty($uri_parts["port"]))
					$this->port = $uri_parts["port"];
				$this->_http_request($method, $params, $this->url, $this->_httpmethod);
				return $this;
				break;
			default:
				// not a valid protocol
				trigger_error('Invalid protocol "' . $uri_parts["scheme"] . '"\n', E_USER_ERROR);
				break;
		}
		return $this;
	} // end of func.

	/**
	 * launch a http request actually.
	 * @param $method
	 * @param array $params
	 * @param $url
	 * @param $http_method
	 * @param string $content_type
	 * @param string $body
	 * @return $this
	 */
	private function _http_request($method, $params = array(), $url, $http_method, $content_type = "", $body = "")
	{
		$this->_prepare_http_headers($url, $http_method);
		if (!empty($this->user) || !empty($this->pass))
		{
			curl_setopt($this->ch, CURLOPT_HTTPAUTH, $this->http_auth);
			curl_setopt($this->ch, CURLOPT_USERPWD, "{$this->user}:{$this->pass}");
		}
		// set the read timeout if needed
		if ($this->timeout > 0)
			curl_setopt($this->ch, CURLOPT_TIMEOUT, $this->timeout);

		if (!empty($this->user) || !empty($this->pass))
		{
			$auth = "{$this->user}:{$this->pass}";
			$start = strpos($url, $auth);
			if ($start !== FALSE) $url = substr_replace($url, "", $start, strlen($auth));
		}
		if (strtolower($http_method) == 'post')
		{
			curl_setopt($this->ch, CURLOPT_HEADER, FALSE);
			curl_setopt($this->ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
			curl_setopt($this->ch, CURLOPT_POST, TRUE);
			$params = json_encode($params);
			curl_setopt($this->ch, CURLOPT_POSTFIELDS, $params);
		} elseif (strtolower($http_method) == 'get') {
			$params = http_build_query($params);
			curl_setopt($this->ch, CURLOPT_POSTFIELDS, $params);
		}
		$url_method = substr($url, -1) === '/' ? $url.$method : $url.'/'.$method;
		curl_setopt($this->ch, CURLOPT_URL, $url_method);
		curl_setopt($this->ch, CURLOPT_RETURNTRANSFER,TRUE);
		$response = curl_exec($this->ch);

		if($response === FALSE) {
			$this->results =  array(
				'error'   => TRUE,
				'error_code'    => curl_errno($this->ch),
				'error_message'  => curl_error($this->ch)
			);
		} elseif(empty($response)){
			$this->results  = array(
				'error' => TRUE,
				'error_code' => '9999',
				'error_message' => 'No Response.'
			);
		} else{
			$this->results = json_decode($response,'array');
		}
		return $this;
	}

	/**
	 * prepare http headers.
	 * @param $url
	 * @param $http_method
	 */
	private function _prepare_http_headers($url, $http_method)
	{
		if (empty($url))
		{
			$url = "/";
		}
		$headers = $http_method . " " . $url . " " . $this->_httpversion . "\r\n";
		if (!empty($this->host) && !isset($this->raw_headers['Host']))
		{
			$headers .= "Host: " . $this->host;
			if (!empty($this->port) && $this->port != '80')
			{
				$headers .= ":" . $this->port;
			}
			$headers .= "\r\n";
		}
		if (!empty($this->agent))
			$headers .= "User-Agent: " . $this->agent . "\r\n";
		if (!empty($this->accept))
			$headers .= "Accept: " . $this->accept . "\r\n";
		if ($this->use_gzip) {
			// make sure PHP was built with --with-zlib
			// and we can handle gzipp'ed data
			if (function_exists('gzinflate')) {
				$headers .= "Accept-encoding: gzip\r\n";
			} else {
				trigger_error(
					"use_gzip is on, but PHP was built without zlib support." .
					"  Requesting file(s) without gzip encoding.",
					E_USER_NOTICE);
			}
		}
		if (!empty($this->referer))
			$headers .= "Referer: " . $this->referer . "\r\n";
		if (!empty($this->raw_headers)) {
			if (!is_array($this->raw_headers))
				$this->raw_headers = (array)$this->raw_headers;
			while (list($headerKey, $headerVal) = each($this->raw_headers))
				$headers .= $headerKey . ": " . $headerVal . "\r\n";
		}
		if (!empty($content_type)) {
			$headers .= "Content-type: $content_type";
			if ($content_type == "multipart/form-data")
				$headers .= "; boundary=" . $this->_mime_boundary;
			$headers .= "\r\n";
		}
		if (!empty($body)) $headers .= "Content-length: " . strlen($body) . "\r\n";
		$headers .= "\r\n";
		curl_setopt($this->ch, CURLOPT_HTTPHEADER, array($headers));
	} // end of func.

	/**
	 * get results of response.
	 * @return string
	 */
	public function get_results()
	{
		return $this->results;
	} // end of func.
}
 CodeIgniter调试代码:
$this->load->library(array('curl'));
$this->curl->user = "ubix";
$this->curl->pass = "u6ix1234";
$res = $this->curl->post()->request('get_machines_info',array('model_numbers'=>array('2', '3')), "http://ims.qdcrx.com/api/machines/")->get_results();
 var_dump($res); exit();

拓展阅读推荐:

(1)https://github.com/php-curl-class/php-curl-class
(2)https://github.com/philsturgeon/codeigniter-curl

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Class Curl
 *
 * Author: Carter
 * Email: carterxin@techtrex.com
 * Date: 2020/10/9
 */
class Curl
{
  /**** Public variables ****/
  /* user definable vars */
  var $url = "";
  var $user = ""; // user for http authentication
  var $pass = ""; // password for http authentication
  var $http_auth = CURLAUTH_ANY;
  var $ssl_verify_peer = FALSE;
  var $ssl_verify_host = FALSE;

  var $port = 80; // port we are connecting to
  var $referer = ""; // referer info to pass
  var $raw_headers = array(); // array of raw headers to send
  var $agent = "";
  // $raw_headers["Content-type"]="text/html";

  // http accept types
  var $accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*";
  var $results = ""; // where the content is put
  var $headers = array(); // headers returned from server sent here
  var $timeout = 30; // timeout on read operations, in seconds
  // send Accept-encoding: gzip?
  var $use_gzip = true;

  /**** Private variables ****/
  private $ch = NULL;
  private $host = "";
  private $_http_method = "GET"; // default http request method
  private $_http_version = "HTTP/1.0"; // default http request version
  private $_mime_boundary = ""; // MIME boundary for multipart/form-data submit type

  /**
   * Curl constructor.
   */
  public function __construct($params)
  {
    $this->ch = curl_init();
    if ($this->ch === FALSE){
      if (!extension_loaded('php_curl')) {
        trigger_error('Curl initialization error, make sure php_curl extension is turned on correctly.', E_USER_ERROR);
        exit;
      }
    }
    $this->init();
    $this->url = $params['base_url'] ?? rtrim($this->config->item('base_url'), '/') . '/api/';
  }

  /**
   * Curl destructor.
   */
  public function __destruct()
  {
    curl_close($this->ch);
  }

  /**
   * Curl initialization.
   */
  public function init()
  {
    if (!isset($this->raw_headers["Content-Type"]))
    {
      $this->raw_headers["Content-Type"]  = "Content-type: text/xml;charset=\"utf-8\"";
    }
    if (!isset($this->raw_headers["Cache-Control"]))
    {
      $this->raw_headers["Cache-Control"] = "No-Cache";
    }
    if (!isset($this->raw_headers["Cache-Control"]))
    {
      $this->raw_headers["Accept"] ="application/json";
    }
  }

  /**
   * Set Post Request.
   * @return $this
   */
  public function post()
  {
    $this->_http_method = "POST";
    return $this;
  }

  /**
   * launch a http request.
   * @param $method api method
   * @param array $params
   * @param string $path_url
   * @return $this
   */
  public function request($method, $params = array(), $path_url = "")
  {
    $this->url = $this->url . $path_url;
    $uri_parts = parse_url($this->url);
    if (!empty($uri_parts["user"]))
      $this->user = $uri_parts["user"];
    if (!empty($uri_parts["pass"]))
      $this->pass = $uri_parts["pass"];
    if (empty($uri_parts["query"]))
      $uri_parts["query"] = '';
    if (empty($uri_parts["path"]))
      $uri_parts["path"] = '';

    switch (strtolower($uri_parts["scheme"])) {
      case "https":
        curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, $this->ssl_verify_peer);
        curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, $this->ssl_verify_host);
        $this->port = 443;
      case "http":
        $this->host = $uri_parts["host"];
        if (!empty($uri_parts["port"]))
          $this->port = $uri_parts["port"];
        $this->_http_request($method, $params, $this->url, $this->_http_method);
        return $this;
        break;
      default:
        // not a valid protocol
        trigger_error('Invalid protocol "' . $uri_parts["scheme"] . '"\n', E_USER_ERROR);
        break;
    }
    return $this;
  } // end of func.

  /**
   * launch a http request actually.
   * @param $method
   * @param array $params
   * @param $url
   * @param $http_method
   * @param string $content_type
   * @param string $body
   * @return $this
   */
  private function _http_request($method, $params = array(), $url, $http_method, $content_type = "", $body = "")
  {
    $this->_prepare_http_headers($url, $http_method);
    if (!empty($this->user) || !empty($this->pass))
    {
      curl_setopt($this->ch, CURLOPT_HTTPAUTH, $this->http_auth);
      curl_setopt($this->ch, CURLOPT_USERPWD, "{$this->user}:{$this->pass}");
    }
    // set the read timeout if needed
    if ($this->timeout > 0)
      curl_setopt($this->ch, CURLOPT_TIMEOUT, $this->timeout);

    if (!empty($this->user) || !empty($this->pass))
    {
      $auth = "{$this->user}:{$this->pass}";
      $start = strpos($url, $auth);
      if ($start !== FALSE) $url = substr_replace($url, "", $start, strlen($auth));
    }
    if (strtolower($http_method) == 'post')
    {
      curl_setopt($this->ch, CURLOPT_HEADER, FALSE);
      curl_setopt($this->ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
      curl_setopt($this->ch, CURLOPT_POST, TRUE);
      $params = json_encode($params);
      curl_setopt($this->ch, CURLOPT_POSTFIELDS, $params);
    } elseif (strtolower($http_method) == 'get') {
      $params = http_build_query($params);
      curl_setopt($this->ch, CURLOPT_POSTFIELDS, $params);
    }
    $url_method = substr($url, -1) === '/' ? $url.$method : $url.'/'.$method;
    curl_setopt($this->ch, CURLOPT_URL, $url_method);
    curl_setopt($this->ch, CURLOPT_RETURNTRANSFER,TRUE);
    $response = curl_exec($this->ch);

    if($response === FALSE) {
      $this->results =  array(
        'error'   => TRUE,
        'error_code'    => curl_errno($this->ch),
        'error_message'  => curl_error($this->ch)
      );
    } elseif(empty($response)){
      $this->results  = array(
        'error' => TRUE,
        'error_code' => '9999',
        'error_message' => 'No Response.'
      );
    } else{
      $this->results = json_decode($response,'array');
    }
    return $this;
  }

  /**
   * prepare http headers.
   * @param $url
   * @param $http_method
   */
  private function _prepare_http_headers($url, $http_method)
  {
    if (empty($url))
    {
      $url = "/";
    }
    $headers = $http_method . " " . $url . " " . $this->_http_version . "\r\n";
    if (!empty($this->host) && !isset($this->raw_headers['Host']))
    {
      $headers .= "Host: " . $this->host;
      if (!empty($this->port) && $this->port != '80')
      {
        $headers .= ":" . $this->port;
      }
      $headers .= "\r\n";
    }
    if (!empty($this->agent))
      $headers .= "User-Agent: " . $this->agent . "\r\n";
    if (!empty($this->accept))
      $headers .= "Accept: " . $this->accept . "\r\n";
    if ($this->use_gzip) {
      // make sure PHP was built with --with-zlib
      // and we can handle gzipp'ed data
      if (function_exists('gzinflate')) {
        $headers .= "Accept-encoding: gzip\r\n";
      } else {
        trigger_error(
          "use_gzip is on, but PHP was built without zlib support." .
          "  Requesting file(s) without gzip encoding.",
          E_USER_NOTICE);
      }
    }
    if (!empty($this->referer))
      $headers .= "Referer: " . $this->referer . "\r\n";
    if (!empty($this->raw_headers)) {
      if (!is_array($this->raw_headers))
        $this->raw_headers = (array)$this->raw_headers;
      while (list($headerKey, $headerVal) = each($this->raw_headers))
        $headers .= $headerKey . ": " . $headerVal . "\r\n";
    }
    if (!empty($content_type)) {
      $headers .= "Content-type: $content_type";
      if ($content_type == "multipart/form-data")
        $headers .= "; boundary=" . $this->_mime_boundary;
      $headers .= "\r\n";
    }
    if (!empty($body)) $headers .= "Content-length: " . strlen($body) . "\r\n";
    $headers .= "\r\n";
    curl_setopt($this->ch, CURLOPT_HTTPHEADER, array($headers));
  } // end of func.

  /**
   * get results of response.
   * @return string
   */
  public function get_results()
  {
    return $this->results;
  } // end of func.
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值