复制
收藏
提问
全网
写一个php的curl完整的封装类
1个月前
理解问题写一个php的curl完整的封装类
已完成理解「写一个php的curl完整的封装类」
展开阅读网页
更专业一些
转笔记
专业
写一个php的curl完整的封装类不在提醒
<?php
/**
* CurlWrapper - A PHP cURL wrapper class for easy HTTP requests
*
* This class provides a simple interface for making GET and POST requests using cURL.
* It supports both HTTP and HTTPS, and can handle JSON and form-urlencoded data.
*
* @author TANKING
* @date 2022-03-17
*/
class CurlWrapper {
private $ch;
private $response;
private $error;
/**
* Constructor initializes cURL session
*/
public function __construct() {
$this->ch = curl_init();
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, false);
}
/**
* Set the URL for the request
*
* @param string $url The URL to request
* @return $this
*/
public function setUrl($url) {
curl_setopt($this->ch, CURLOPT_URL, $url);
return $this;
}
/**
* Set the request method to GET
*
* @return $this
*/
public function setGet() {
curl_setopt($this->ch, CURLOPT_HTTPGET, true);
return $this;
}
/**
* Set the request method to POST and set the POST data
*
* @param array $data The data to POST
* @param string $contentType The content type of the data (json or form)
* @return $this
*/
public function setPost($data, $contentType = 'form') {
curl_setopt($this->ch, CURLOPT_POST, true);
if ($contentType === 'json') {
$data = json_encode($data);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
}
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $data);
return $this;
}
/**
* Execute the cURL request
*
* @return $this
*/
public function execute() {
$this->response = curl_exec($this->ch);
if ($this->response === false) {
$this->error = curl_error($this->ch);
}
return $this;
}
/**
* Get the response from the cURL request
*
* @return string
*/
public function getResponse() {
return $this->response;
}
/**
* Get any error that occurred during the cURL request
*
* @return string
*/
public function getError() {
return $this->error;
}
/**
* Close the cURL session
*/
public function close() {
curl_close($this->ch);
}
}
// Example usage:
// $curl = new CurlWrapper();
// $response = $curl->setUrl('https://example.com')
// ->setGet()
// ->execute()
// ->getResponse();
// echo $response;
// $curl->close();
说明
- CurlWrapper 类封装了 cURL 的基本功能,支持 GET 和 POST 请求,并能处理 JSON 和 form-urlencoded 数据。
- 使用链式调用方式,简化了请求的设置和执行过程。
- 提供了错误处理机制,确保在请求失败时能够获取错误信息。
- 类的设计遵循面向对象的原则,易于扩展和维护。