Skip to content

Instantly share code, notes, and snippets.

@RobertWang
Created March 21, 2014 07:19
Show Gist options
  • Save RobertWang/9681214 to your computer and use it in GitHub Desktop.
Save RobertWang/9681214 to your computer and use it in GitHub Desktop.
[php]CURL GET/POST
<?php
/**
* 提交GET请求,curl方法
* @param string $url 请求url地址
* @param mixed $data GET数据,数组或类似id=1&k1=v1
* @param array $header 头信息
* @param int $timeout 超时时间
* @param int $port 端口号
* @return array 请求结果,
* 如果出错,返回结果为array('status'=>false,'error'=>'','result'=>''),
* 未出错,返回结果为array('status'=>true,'result'=>''),
*/
function curl_get($url, $data = array(), $header = array(), $timeout = 5, $port = 80)
{
$ch = curl_init();
if (!empty($data)) {
$data = is_array($data)?http_build_query($data): $data;
$url .= (strpos($url,'?')? '&': "?") . $data;
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_POST, 0);
//curl_setopt($ch, CURLOPT_PORT, $port);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = array('status'=>true);
$result['result'] = curl_exec($ch);
if (0 != curl_errno($ch)) {
$result['error'] = "Error:\n" . curl_error($ch);
$result['status'] = false;
}
curl_close($ch);
return $result;
}
/**
* 提交POST请求,curl方法
* @param string $url 请求url地址
* @param mixed $data POST数据,数组或类似id=1&k1=v1
* @param array $header 头信息
* @param int $timeout 超时时间
* @param int $port 端口号
* @return string 请求结果,
* 如果出错,返回结果为array('status'=>false,'error'=>'','result'=>''),
* 未出错,返回结果为array('status'=>true,'result'=>''),
*/
function curl_post($url, $data = array(), $header = array(), $timeout = 5, $port = 80)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
//curl_setopt($ch, CURLOPT_PORT, $port);
!empty ($header) && curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = array('status'=>true);
$result['result'] = curl_exec($ch);
if (0 != curl_errno($ch)) {
$result['error'] = "Error:\n" . curl_error($ch);
$result['status'] = false;
}
curl_close($ch);
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment