助力软件开发企业降本增效 PHP / java源码系统,只需一次付费,代码终身使用! 广告
## CURL 操作 PHP 支持 Daniel Stenberg 创建的 libcurl 库,能够连接通讯各种服务器、使用各种协议。libcurl 目前支持的协议有 http、https、ftp、gopher、telnet、dict、file、ldap。 libcurl 同时支持 HTTPS 证书、HTTP POST、HTTP PUT、 FTP 上传(也能通过 PHP 的 FTP 扩展完成)、HTTP 基于表单的上传、代理、cookies、用户名+密码的认证。 更多关于 CURL 请参考:[传送门](http://php.net/manual/zh/book.curl.php) 使用 CURL 函数的基本步骤: * 首先使用 curl_init() 初始化 cURL会话。 * 接着通过 curl_setopt() 设置需要的全部选项。 * 然后使用 curl_exec() 来执行会话。 * 最后使用 curl_close() 关闭会话。 ### CURL 发送 HTTP 请求 ``` <?php class HttpClient { private $url = ''; // url private $body = []; // 请求正文 private $headers = []; // 请求头 public function __construct($url = null) { if ($url) { $this->setUrl($url); } } /** * 设置URL * @param string $url */ public function setUrl($url) { $this->url = $url; } /** * 添加请求头信息 * @param string $header */ public function setHeader($header) { $this->headers[] = $header; } /** * 构造消息正文 * @param array */ private function setBody($data) { $this->body = $data; } /** * GET 请求 * @return array */ public function get() { return this->request(); } /** * POST 请求 * @param array $data * @return array */ public function post($data = []) { $this->setHeader('Expect:'); $this->setBody($data); return $this->request(); } private function request() { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->url); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if ($this->headers) { curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers); } if ($this->body) { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->body); } $response = curl_exec($ch); curl_close($ch); list($headers, $content) = explode("\r\n\r\n", $response); return [ 'headers' => $headers, 'content' => $content, ]; } } $http = new HttpClient('http://forum-api.local/test'); /* ------------- 发送 GET 请求 ------------ */ $response = $http->get(); var_dump($response['headers']); var_dump($response-['content']); exit(); /* ------------- 发送 POST 请求 ------------ */ $data = [ 'name' => 'kate green', 'age' => 12, ]; $response = $http->post($data); var_dump($response['headers']); var_dump($response['content']); ?> ```