首頁  >  文章  >  php框架  >  thinkphp取得不到post資料如何解決

thinkphp取得不到post資料如何解決

WBOY
WBOY轉載
2023-05-29 21:25:102123瀏覽

一、問題現象

提交表單後,透過request->param() 或$this->request->param()取得不到post 數據,得到的是空數組。

二、問題原因

  1. 表單中沒有設定enctype 屬性

在表單提交時,如果enctype 屬性沒有設置,那麼預設的資料傳輸方式就是application/x-www-form-urlencoded。現在,資料將被放置在 HTTP 請求頭部而非請求體中。所以,在取得 post 資料時,我們需要使用 $this->request->post() 或 request()->post()。

  1. 介面呼叫時沒有設定請求頭

在介面呼叫時,我們需要設定對應的請求頭,例如Content-Type:application /json,否則伺服器無法解析資料。如果沒有設定 Content-Type,則伺服器預設為 application/x-www-form-urlencoded,而此時 post 的資料會放在 http 請求頭中,而不是請求體中,導致無法正確取得 post 資料。

三、解決方法

  1. 設定enctype 屬性

在表單中加入enctype=" multipart/form-data",這樣就能夠正確取得post 資料了。

  1. 設定請求頭

在介面呼叫時,可以使用 curl 設定請求頭。範例程式碼如下:

$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);

以上是thinkphp取得不到post資料如何解決的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除