1.封装请求函数
if(!function_exists('curl_request')){
//发送curl请求
function curl_request($url, $type = false, $params = [], $https=false)
{
//调用curl_init() 初始化请求
$ch = curl_init($url);
//调用curl_setopt()设置请求选项
if($type){
//true 发送post请求 false 默认发送get请求
//post请求 设置请求方式
curl_setopt($ch, CURLOPT_POST, true);
//设置请求参数
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
}
//如果是https请求 需要禁止从服务器端验证本地的证书
if($https){
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
//调用curl_exec() 发送请求 获取结果
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
// if(!$res){
// //错误信息
// $error = curl_error($ch);
// //错误码
// $errno = curl_errno($ch);
// }
//调用curl_close() 关闭请求
curl_close($ch);
return $res;
}
}
2.使用请求函数
public function testrequest()
{
// 接口地址 http://www.tpshop.com/api/index/testapi
$url = "http://www.tpshop.com/api/index/testapi";
// 请求方式 get
// 请求参数 id page
// $params = ['id' => 100, 'page' => 10];
// $url .= '?id=100&page=10';
// 发送请求
// $res = curl_request($url, false, [], false);
// $res = curl_request($url);
// dump($res);die;
// 请求方式 post
// 请求参数 id page
$params = ['id' => 100, 'page' => 10];
// 发送请求
// $res = curl_request($url, true, $params, false);
$res = curl_request($url, true, $params);
// 结果的处理
if(!$res){
echo '请求错误';die;
}
// 解析结果 $res = '{"code"=>200,"msg"=>"success", "data"=>{}}';
$arr = json_decode($res, true);
dump($arr['data']);
dump($res);die;
}