- 客戶端請求時,請求頭帶有信息,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', ];