cURL是一个强壮的库,也许衔接通讯各样任职器、利用各样协议。同时赞成 HTTPS 证书、HTTP POST、HTTP PUT、 FTP 上传(也能经过 PHP 的 FTP 扩展完成)、HTTP 基于表单的上传、代办、cookies、用户名+暗码的认证。
2. 实现措施:
初始化一个会话
设备 cURL 选项
施行会话
封闭会话
3. 下面封装的一个实例,赞成get,post两种类别
该实例,便于接口对接利用
date_default_timezone_set('PRC');//设备时区/** * 发送API * demo仅供参考,demo最低运行处境PHP5.3 * 请确认开启PHP CURL 扩展 */class sendAPI { public $data; //发送数据 public $timeout = 30; //超时 private $apiUrl; //发送所在 private $username; //用户名 private $password; //暗码 function __construct($url, $username, $password) { $this->apiUrl = $url; $this->username = $username; $this->password = $password; } private function httpGet() { $url = $this->apiUrl . '?' . http_build_query($this->data); $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_URL, $url); $res = curl_exec($curl); if (curl_errno($curl)) { echo 'Error GET '.curl_error($curl); } curl_close($curl); return $res; } private function httpPost(){ // 模仿提交数据函数 $curl = curl_init(); // 启动一个CURL会话 curl_setopt($curl, CURLOPT_URL, $this->apiUrl); // 要拜访的所在 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来历的查抄 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中查抄SSL加密算法是否存在 curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模仿用户利用的阅读器 curl_setopt($curl, CURLOPT_POST, true); // 发送一个常例的Post央求 curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($this->data)); // Post提交的数据包 curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout); // 设备超时控制预防死循环 curl_setopt($curl, CURLOPT_HEADER, false); // 显现返回的Header地区内容 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的式样返回 $result = curl_exec($curl); // 施行操纵 if (curl_errno($curl)) { echo 'Error POST'.curl_error($curl); } curl_close($curl); // 要害CURL会话 return $result; // 返回数据 } /** * @param $type|提交类别 POST/GET * @param $isTranscoding|是否必要转 $isTranscoding 是否必要转utf-8 默认 false * @return mixed */ public function sendSMS($type, $isTranscoding = false) { $this->data['content'] = $isTranscoding === true ? mb_convert_encoding($this->data['content'], "UTF-8") : $this->data['content']; $this->data['username'] = $this->username; $this->data['tkey'] = date('YmdHis'); $this->data['password'] = md5(md5($this->password) . $this->data['tkey']); return $type == "POST" ? $this->httpPost() : $this->httpGet(); }}