一、問題現(xiàn)象
提交表單后,通過 request->param() 或 $this->request->param() 獲取不到 post 數(shù)據(jù),得到的是空數(shù)組。
二、問題原因
-
表單中沒有設(shè)置 enctype 屬性
立即學(xué)習(xí)“PHP免費(fèi)學(xué)習(xí)筆記(深入)”;
在表單提交時,如果 enctype 屬性沒有設(shè)置,那么默認(rèn)的數(shù)據(jù)傳輸方式是 application/x-www-form-urlencoded。現(xiàn)在,數(shù)據(jù)將被放置在 HTTP 請求頭部而非請求體中。所以,在獲取 post 數(shù)據(jù)時,我們需要使用 $this->request->post() 或者 request()->post()。
-
接口調(diào)用時沒有設(shè)置請求頭
在接口調(diào)用時,我們需要設(shè)置相應(yīng)的請求頭,比如 Content-Type:application/json,否則服務(wù)器無法解析數(shù)據(jù)。如果沒有設(shè)置 Content-Type,則服務(wù)器默認(rèn)為 application/x-www-form-urlencoded,而此時 post 的數(shù)據(jù)會放在 http 請求頭中,而不是請求體中,導(dǎo)致無法正確獲取 post 數(shù)據(jù)。
三、解決方法
-
設(shè)置 enctype 屬性
在表單中添加 enctype=”multipart/form-data”,這樣就能夠正確獲取 post 數(shù)據(jù)了。
-
設(shè)置請求頭
在接口調(diào)用時,可以使用 curl 設(shè)置請求頭。示例代碼如下:
$data?=?array( ????'username'?=>?'admin', ????'password'?=>?'123456' ); $url?=?'http://www.example.com/login'; $ch?=?curl_init(); $header?=?array( ????'Content-Type:?application/json', ????'Content-Length:?'.strlen(json_encode($data)) ); curl_setopt($ch,?CURLOPT_URL,?$url); curl_setopt($ch,?CURLOPT_POST,?1); curl_setopt($ch,?CURLOPT_POSTFIELDS,?json_encode($data)); curl_setopt($ch,?CURLOPT_HTTPHEADER,?$header); curl_setopt($ch,?CURLOPT_RETURNTRANSFER,?1); $res?=?curl_exec($ch); curl_close($ch);