You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

114 lines
3.5 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace LaneWeChat\Core; // 定义命名空间为 LaneWeChat\Core表示该类属于 LaneWeChat 模块的核心部分
/**
* CURL工具类用于简化HTTP请求操作。
*
* 该类提供了一系列方法来执行HTTP请求包括GET、POST、PUT、DELETE和HEAD请求。
*
* @author Lane
* @email lixuan868686@163.com
* @website http://www.lanecn.com
*/
class Curl {
// 私有静态变量用于存储CURL会话句柄、头部、主体等信息
private static $_ch;
private static $_header;
private static $_body;
// 存储Cookie、选项、URL和Referer的数组
private static $_cookie = array();
private static $_options = array();
private static $_url = array();
private static $_referer = array();
/**
* 调用外部URL支持GET和POST请求。
*
* @param string $queryUrl 请求的URL
* @param array|string $param 参数
* @param string $method 请求方法,默认为'get'
* @param bool $is_json 是否将返回结果解析为JSON默认为true
* @param bool $is_urlcode 是否对参数进行URL编码默认为true
* @return bool|mixed 返回请求结果或false
*/
public static function callWebServer($queryUrl, $param = '', $method = 'get', $is_json = true, $is_urlcode = true) {
// 检查URL是否为空
if (empty($queryUrl)) {
return false;
}
// 转换方法为小写
$method = strtolower($method);
$ret = '';
// 确保参数是数组
$param = empty($param) ? array() : $param;
// 初始化CURL会话
self::_init();
// 根据请求方法调用相应的私有方法
if ($method == 'get') {
$ret = self::_httpGet($queryUrl, $param);
} elseif ($method == 'post') {
$ret = self::_httpPost($queryUrl, $param, $is_urlcode);
}
// 如果有返回结果根据参数决定是否解析为JSON
if (!empty($ret)) {
if ($is_json) {
return json_decode($ret, true);
} else {
return $ret;
}
}
return false;
}
/**
* 初始化CURL会话
*/
private static function _init() {
self::$_ch = curl_init();
// 设置CURL选项
curl_setopt(self::$_ch, CURLOPT_HEADER, true);
curl_setopt(self::$_ch, CURLOPT_RETURNTRANSFER, true);
}
/**
* 设置CURL选项
*
* @param array $optArray 选项数组
*/
public static function setOption($optArray = array()) {
foreach ($optArray as $opt) {
curl_setopt(self::$_ch, $opt['key'], $opt['value']);
}
}
/**
* 关闭CURL会话
*
* @return bool
*/
private static function _close() {
if (is_resource(self::$_ch)) {
curl_close(self::$_ch);
}
return true;
}
/**
* 发送GET请求
*
* @param string $url 请求URL
* @param array $query 查询参数
* @return mixed 请求结果
*/
private static function _httpGet($url, $query = array()) {
// 构建查询字符串
if (!empty($query)) {
$url .= (strpos($url, '?') === false) ? '?' : '&';
$url .= is_array($query) ? http_build_query($query) : $query;
}
// 设置CURL选项
curl_setopt(self::$_ch, CURLOPT_URL, $url);
curl_setopt(self::$_ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(self::$_ch, CURLOPT_HEADER, 0);
// 禁用