curlGet,curlPost
/**
* curl get 请求
* @param string $url
* @param array $options 关联数组(一维),如:[CURLOPT_URL => 'http://www.example.com/',CURLOPT_POST => 1]
* @param int $CURLOPT_TIMEOUT 设置cURL允许执行的最长秒数
* @param callable $success_fn
* @param callable $fail_fn
* @return mixed
*/
function curlGet($url = '', $options = array(), $CURLOPT_TIMEOUT = 30, $success_fn = '', $fail_fn = '')
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, $CURLOPT_TIMEOUT);
if (!empty($options)) {
curl_setopt_array($ch, $options);
}
//https请求 不验证证书和host
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($ch);
if (curl_errno($ch)) {
if (is_callable($fail_fn)) {
$fail_fn($ch);
} else {
//打印错误信息
var_dump(curl_error($ch));
}
} else {
is_callable($success_fn) && $success_fn($ch);
}
curl_close($ch);
return $data;
}
/**
* @param string $url
* @param string|array $postData post请求传输的数据
* @param array $options 关联数组(一维),如:[CURLOPT_URL => 'http://www.example.com/',CURLOPT_POST => 1]
* @param int $CURLOPT_TIMEOUT 设置cURL允许执行的最长秒数
* @param callable $success_fn
* @param callable $fail_fn
* @return mixed
*/
function curlPost($url = '', $postData = '', $options = array(), $CURLOPT_TIMEOUT = 30, $success_fn = '', $fail_fn = '')
{
if (is_array($postData)) {
$postData = http_build_query($postData);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_TIMEOUT, $CURLOPT_TIMEOUT); //设置cURL允许执行的最长秒数
if (!empty($options)) {
curl_setopt_array($ch, $options);
}
//https请求 不验证证书和host
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($ch);
if (curl_errno($ch)) {
is_callable($fail_fn) && $fail_fn($ch);
} else {
is_callable($success_fn) && $success_fn($ch);
}
curl_close($ch);
return $data;
}