PHP 获取请求里的 header字段以及发送header

  • 客户端请求时,请求头带有信息,PHP如何获取header:https://blog.csdn.net/ljh243581579/article/details/84066853
  • header保存在$_SERVER数组里,可以通过打印$_SERVER 数组查看里面的字段名称。比如客户端请求的字段里有time,$_SERVER['HTTP_TIME'];  需要加上HTTP_  前缀,并且大写。
  • 发送header可以通过curl , 示例如下
    function curlGet($url, $header)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
    
    $header = [
        'grant_type:type',     //注意数据格式使用冒号
        'appid:2231777777777777777',  //在接受的时候,$_SERVER['HTTP_APPID'];
        'secret:fdsjg',
    ];
  • curl以post方式发送json数据,需要在$header 里加入
      function curlPost($url, $param, $header = [])
        {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            //设置头文件的信息作为数据流输出
            curl_setopt($ch, CURLOPT_HEADER, 1);
            //设置获取的信息以文件流的形式返回,而不是直接输出。
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            //设置post方式提交
            curl_setopt($ch, CURLOPT_POST, 1);
            //设置post数据
            $post_data = $param;
            $json_data = json_encode($post_data)
            curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
            // 发送header字段
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            //执行命令
            $data = curl_exec($ch);
            curl_close($ch);
            return $data;
        }
    // 设置header ,并且注意将post参数转换成json格式数据
    $header = [
                'Content-Type: application/json; charset=utf-8',
            ];
    post方式发送json
原文地址:https://www.cnblogs.com/bneglect/p/12358003.html