php curl
直接上代码
代码语言:javascript复制 /**
* @param string $url
* @param array $params
* @param bool $post
* @return string
*/
function httpRequest($url, $params, $post = true)
{
$header = [
'Content-Type: application/json; charset=utf-8',
];
$ch = curl_init();
if ($post) {
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
} elseif (is_array($params) && 0 < count($params)) {
curl_setopt($ch, CURLOPT_URL, $url . "?" . http_build_query($params));
} else {
curl_setopt($ch, CURLOPT_URL, $url);
}
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FORBID_REUSE, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$data = curl_exec($ch);
if (curl_error($ch)) {
trigger_error(curl_error($ch));
return null;
}
curl_close($ch);
return $data;
}
post方式提交使用案例:
代码语言:javascript复制$url = 'http://www.litblc.com/login.php';
$params = ['username' => 'test', 'pwd' => '123456'];
$data = httpRequest($url, $params, true);
那么,在login.php就可以使用post方式获取username、pwd
get方式提交使用案例:
代码语言:javascript复制$url = 'http://www.litblc.com/actrile?id=123456';
$params = [];
$data = httpRequest($url, $params, false);
由于是get方式,将函数的第三个参数post置为false;同时要注意你的url和params,参数可以直接放在url中,那么params就是空值
https
请求https的uri由于检查证书会报错,解决方案是去http://curl.haxx.se/ca/cacert.pem
下载最新证书到本地,然后在php.ini中引入,以windows为例:curl.cainfo = D:/wamp/php-7.2.7-nts-Win32-VC15-x64/cacert.pem
。重启服务器。