<?php
/**
*
* @example
*
* 1. 基本 get 请求:
* $http = new Requests(); // 实例化对象
* $result = $http->get('http://www.***.com/');
* 2. 基本 post 请求:
* $http = new Requests(); // 实例化对象
* $result = $http->post('http://www.***.com/', array('title'=>$title, 'body'=>$body) );
*
* */
class Requests
{
public $option = [
//请求超时时间, 默认是 25
'timeout' => 25,
//请求客户端 User agent
'userAgent' => "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7",
//referrer 信息
'referrer' => '',
];
public function __construct()
{
}
function setOption($option)
{
$this->option = array_merge($this->option, $option);
return $this;
}
public function get($url, $data = array())
{
return $this->execute($url, '', 'GET', $data);
}
public function post($url, $data = array())
{
return $this->execute($url, '', 'POST', $data);
}
private function execute($target, $referrer = '', $method = '', $data = array())
{
$ch = curl_init();
if (is_array($data) && count($data) > 0) {
$queryString = http_build_query($data);
}
if ($method == 'GET') {
curl_setopt($ch, CURLOPT_HTTPGET, TRUE);
curl_setopt($ch, CURLOPT_POST, FALSE);
if (isset($queryString)) {
$target = $target . (strstr($target, '?') !== false ? '&' : '?') . $queryString;
}
} else {
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPGET, FALSE);
if (isset($queryString)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $queryString);
}
}
// 这是你想用PHP取回的URL地址。你也可以在用curl_init()函数初始化时设置这个选项。
curl_setopt($ch, CURLOPT_URL, $target);
//如果你不想在输出中包含body部分,设置这个选项为一个非零值。
curl_setopt($ch, CURLOPT_NOBODY, FALSE);
//默认超时为0(零),这意味着它在传输过程中永不超时。
curl_setopt($ch, CURLOPT_TIMEOUT, $this->option['timeout']);
//在HTTP请求中包含一个”user-agent”头的字符串。
curl_setopt($ch, CURLOPT_USERAGENT, $this->option['userAgent']);
//在HTTP请求中包含一个”referer”头的字符串。
curl_setopt($ch, CURLOPT_REFERER, $this->option['referrer']);
// 如果你想CURL报告每一件意外的事情,设置这个选项为一个非零值。
curl_setopt($ch, CURLOPT_VERBOSE, FALSE);
//设为0表示不检查证书
//设为1表示检查证书中是否有CN(common name)字段
//设为2表示在1的基础上校验当前的域名是否与CN匹配
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//设定返回的数据是否自动显示
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
$content = curl_exec($ch);
if ($content) {
curl_close($ch);
return $content;
} else {
$error = curl_errno($ch);
curl_close($ch);
throw new \Exception("curl出错,错误码:$error");
}
}
}