我是靠谱客的博主 着急果汁,最近开发中收集的这篇文章主要介绍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 . "rn";
if (!empty($this->host) && !isset($this->raw_headers['Host']))
{
$headers .= "Host: " . $this->host;
if (!empty($this->port) && $this->port != '80')
{
$headers .= ":" . $this->port;
}
$headers .= "rn";
}
if (!empty($this->agent))
$headers .= "User-Agent: " . $this->agent . "rn";
if (!empty($this->accept))
$headers .= "Accept: " . $this->accept . "rn";
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: gziprn";
} 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 . "rn";
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 . "rn";
}
if (!empty($content_type)) {
$headers .= "Content-type: $content_type";
if ($content_type == "multipart/form-data")
$headers .= "; boundary=" . $this->_mime_boundary;
$headers .= "rn";
}
if (!empty($body)) $headers .= "Content-length: " . strlen($body) . "rn";
$headers .= "rn";
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 . "rn";
if (!empty($this->host) && !isset($this->raw_headers['Host']))
{
$headers .= "Host: " . $this->host;
if (!empty($this->port) && $this->port != '80')
{
$headers .= ":" . $this->port;
}
$headers .= "rn";
}
if (!empty($this->agent))
$headers .= "User-Agent: " . $this->agent . "rn";
if (!empty($this->accept))
$headers .= "Accept: " . $this->accept . "rn";
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: gziprn";
} 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 . "rn";
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 . "rn";
}
if (!empty($content_type)) {
$headers .= "Content-type: $content_type";
if ($content_type == "multipart/form-data")
$headers .= "; boundary=" . $this->_mime_boundary;
$headers .= "rn";
}
if (!empty($body)) $headers .= "Content-length: " . strlen($body) . "rn";
$headers .= "rn";
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.
}

 

最后

以上就是着急果汁为你收集整理的PHP Curl 封装类 [ [ Curl.class ] ]的全部内容,希望文章能够帮你解决PHP Curl 封装类 [ [ Curl.class ] ]所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(48)

评论列表共有 0 条评论

立即
投稿
返回
顶部