HTTP協(xié)議中的POST 方法有多中格式的數(shù)據(jù)協(xié)議,在HTTP的head中用不同的Content-type標(biāo)識.常用的有
application/x-www-form-urlencoded,這是最常見的,就是from表單的格式.在HTTP的head中是Content-Type:
application/x-www-form-urlencoded.
multipart/form-data,這個是用來上傳文件的,在HTTP的head中是Content-Type: multipart/form-data;
boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Raw 這個不是特別常用,傳輸?shù)臄?shù)據(jù)在HTTP的body中只有一段,不是以鍵值對的形式存放.在HTTP的head中是Content-Type:
application/json,Content-Type: text,Content-Type: application/xml,Content-Type:
text/xml,等等形式
對于Content-Type: application/x-www-form-urlencoded這種form表單的數(shù)據(jù),在php中,使用
$_POST['name']可以直接獲取, 沒有什么特別的
Content-Type: multipart/form-data; 這種格式的數(shù)據(jù),在php中使用$_POST['name']可以獲取字符數(shù)據(jù),使用
$_FILES['file']可以獲取.
對于Raw這種格式的數(shù)據(jù),使用以上兩種辦法沒有辦法獲取到,需要使用別的手段.
1.使用file_get_contents("php://input")獲取;寫一個簡單php文件測試一下
<?php $test=file_get_contents("php://input"); echo $test;
用postman測試一下
沒問題,可以接收到
2.使用$GLOBALS['HTTP_RAW_POST_DATA']接收
<?php $test=$GLOBALS['HTTP_RAW_POST_DATA']; echo $test;
用postman測試一下
臥槽,竟然出錯了,提示沒有發(fā)現(xiàn)HTTP_RAW_POST_DATA這個數(shù)組索引,什么鬼.Google一番,在php的官網(wǎng)看到了這樣一段話
原來HTTP_RAW_POST_DATA這個在php5.6中已經(jīng)被廢棄了,在php7.0以后的版本中已經(jīng)被刪除了,我用的php版本為7.2,肯定就出錯了
好吧,那就老老實(shí)實(shí)的用file_get_contents("php://input")獲取吧
在實(shí)際開發(fā)中,一般都是使用框架的,我用thinkphp用比較多,在tp5.0中可以使用Request的getInput()函數(shù)獲取Raw中的數(shù)據(jù)
<?php namespace app\index\controller; use think\Request; class Index { public
function index(Request $request) { echo $request->getInput(); } }
測試一下
沒有問題,可以正常獲取
關(guān)于php獲取HTTP POST數(shù)據(jù)的方法先介紹到這里
熱門工具 換一換