curl请求函数

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;
}


相关推荐

  • 生成图片

    from PIL import Image, ImageColor, ImageDraw, ImageFont, ImageFilterdef create_image_with_text(size, color, text, font_path, font_size, text_color, shadow_color, output_path): """ Create a new image of specified size and color with centered text that has a border and shadow. :param size: A tuple con

  • 获取指定目录下的所有图片信息

    1 获取指定目录下的所有图片信息// 获取指定目录下的所有图片信息 public function getImagesInfo($directory) { $images = []; // 创建递归目录迭代器 $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY ); // 遍历目录中的每个文件 foreach (

  • Thinkphp各版本的PHP要求

    ThinkPHP 8.0:运行环境要求PHP8.0+,兼容PHP8.3ThinkPHP 6.1:运行环境要求PHP7.2+,兼容PHP8.1ThinkPHP 6.0:运行环境要求PHP7.2+,兼容PHP8.1ThinkPHP 5.1:运行环境要求PHP5.6+,兼容PHP8.0ThinkPHP 5.0:运行环境要求PHP5.4+,兼容PHP7.3