第一种方法POST 和 GET 合并
function http_curl($url, $type = 'get', $data = ''){
$cl = curl_init(); //初始化
curl_setopt($cl, CURLOPT_URL, $url); //设置 cURL 传输选项
curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1); // 将curl_exec()获取的信息以字符串返回,而不是直接输出。
curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, false);
if($type == 'post'){
curl_setopt($cl, CURLOPT_POST, 1); //发送 POST 请求,类型为:application/x-www-form-urlencoded
curl_setopt($cl, CURLOPT_POSTFIELDS, $data);
}
$output = curl_exec($cl); //执行 cURL 会话
curl_close($cl);
return $output;
}
第二种方法 POST 和 GET分开
POST
function http_post($url, $params, $header = ['Content-Type: text/plain']) {
$opts = [
CURLOPT_TIMEOUT => 30,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => $header
];
$opts[CURLOPT_URL] = $url;
$opts[CURLOPT_POST] = 1;
$opts[CURLOPT_POSTFIELDS] = $params;
/* 初始化并执行curl请求 */
$ch = curl_init();
curl_setopt_array($ch, $opts);
$data = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
return $data;
}
GET
function http_get($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
// 为保证第三方服务器与微信服务器之间数据传输的安全性,如果是采用https方式调用,必须使用下面2行代码打开ssl安全校验。
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_URL, $url);
$res = curl_exec($curl);
curl_close($curl);
return $res;
}