PHP和CURL
随着移动互联网的发展,移动办公的需求在需要改变以适应现在环境的传统企业中变得越来越大。这类的移动应用和企业的业务需要密切相关,可能只使用本企业,一般并发用户少,在初期需求不明确,改变比较大,那对应用的开发迭代要求高。在这类的应用的后台,PHP+json是很好的选择,后台更新方便,而且可利用资源较多。
其和公司业务相关,可能需要请求其他的REST服务,那么在PHP中和其他的第三方的服务怎么打交道,CURL是很好的选择,我感觉其想较与C的API很好用。
CURL工作的流程一般按以下流程:
- curl int
- curl set option
- curl exec
- curl close对于各种协议,请求方式的不同,在
set option
中完成设置。对于各option
的选择PHP手册有详细的说明。下面是我简单的封装。
<?php
class Request
{
public function __construct() {
$this->url = NULL;
$this->headers = array('Content-Type' => 'application/json');;
$this->body = NULL;
$this->query_string = NULL;
$this->time_out = 0;
}
public $url;
public $headers;
public $body;
public $query_string;
public $time_out;
}
class HttpAct
{
private $curl = NULL;
public function __construct() {
if (!$this->curl) {
$this->curl = curl_init();
if (!$this->curl) {
echo 'curl inti error!';
}
}
}
public function __destruct() {
if ($this->curl) {
curl_close($this->curl);
}
}
public function get($request) {
if ($this->curl) {
$_url = $request->url;
if ($request->query_string) {
$_url = $_url."?".$this->query_string;
}
curl_setopt($this->curl, CURLOPT_URL, $_url);
curl_setopt($this->curl, CURLOPT_HTTPGET, 1);
curl_setopt($this->curl, CURLOPT_TIMEOUT, $request->time_out);
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $request->headers);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($this->curl);
if (curl_errno($this->curl)) {
} else {
return $data;
}
}
}
public function post($request) {
if ($this->curl) {
curl_setopt($this->curl, CURLOPT_URL, $request->url);
curl_setopt($this->curl, CURLOPT_POST, 1);
curl_setopt($this->curl, CURLOPT_TIMEOUT, $request->time_out);
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $request->headers);
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $request->body);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($this->curl);
if (curl_errno($this->curl)) {
} else {
echo $data;
}
}
}
}
$request = new Request();
$request->url = 'http://www.baidu.com';
$request->time_out = 1;
$httpact = new HttpAct();
$data = $httpact->get($request);
if ($data) {
echo $data;
} else {
echo 'error';
}
?>
运行的效果如下: