您的位置:首页 > 编程语言 > PHP开发

php curl请求封装(备份,万一下次用到了,直接copy哈哈哈)

2015-10-29 16:11 603 查看
/**

* 发起get或者post请求

* @param string $url Url to request

* @param array $params Parameters for the request

* @param string $httpMethod Http method, 'GET' or 'POST'

* @return string|false Returns string if success, or false if failed

*/

private static function request($url, $params = array(), $httpMethod = 'GET')

{

$ch = curl_init();

$curl_opts = array(

CURLOPT_CONNECTTIMEOUT => 3,

CURLOPT_TIMEOUT => 5,

CURLOPT_USERAGENT => 'jd',

CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,

CURLOPT_RETURNTRANSFER => true,

CURLOPT_HEADER => false,

CURLOPT_FOLLOWLOCATION => false,

);

if (stripos($url, 'https://') === 0) {

$curl_opts[CURLOPT_SSL_VERIFYPEER] = false;

}

if (strtoupper($httpMethod) === 'GET') {

$query = http_build_query($params, '', '&');

$delimiter = strpos($url, '?') === false ? '?' : '&';

$curl_opts[CURLOPT_URL] = $url . $delimiter . $query;

$curl_opts[CURLOPT_POST] = false;

} else {

$body = http_build_query($params, '', '&');

$curl_opts[CURLOPT_URL] = $url;

$curl_opts[CURLOPT_POSTFIELDS] = $body;

}

curl_setopt_array($ch, $curl_opts);

$result = curl_exec($ch);

curl_close($ch);

if (($result === false) || empty($result)) {

return false;

}

return $result;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: