<?php
header("Content-type: text/html; charset=utf-8");
/**
* curl 传递数据
*/
class curl {
private $curl_resource;
private $url = '';
private $input = array();
private $curl_error = '';
private $curl_info = '';
public $response;
public function __construct($url) {
$this->url = $url;
}
public function get_info() {
return array('url'=>$this->url,'input'=>$this->input,'curl_error'=>$this->curl_error,'curl_info'=>$this->curl_info);
}
private function connect() {
$this->curl_resource = curl_init();
curl_setopt($this->curl_resource, CURLOPT_HEADER, 0 ); // 过滤HTTP头
curl_setopt($this->curl_resource,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
curl_setopt($this->curl_resource, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
}
public function post($input) {
$this->connect();
$input = (array) $input;
$this->input = $input;
$input = http_build_query($input); //根据数组产生一个urlencode之后的请求字符串
curl_setopt($this->curl_resource, CURLOPT_URL, $this->url);
curl_setopt($this->curl_resource,CURLOPT_POST,true); // post传输数据
curl_setopt($this->curl_resource,CURLOPT_POSTFIELDS,$input); // post传输数据
$this->curl_error = curl_error($this->curl_resource);
$this->curl_info = curl_getinfo($this->curl_resource);
$this->response = curl_exec($this->curl_resource);
curl_close($this->curl_resource);
return $this->response;
}
public function get($input) {
$this->connect();
$input = (array) $input;
$this->input = $input;
$input = $this->url.'?'.http_build_query($input);
curl_setopt($this->curl_resource, CURLOPT_URL, $input);
$this->response = curl_exec($this->curl_resource);
curl_close($this->curl_resource);
return $this->response;
}
}
$curl = new curl('http://www.test.com/index.php');
print_r($curl->post('post传递数据'));
var_dump($curl->get_info());
print_r($curl->get('get传递数据'));
var_dump($curl->get_info());