1. 程式人生 > >原生PHP接收$_POST的幾種方式

原生PHP接收$_POST的幾種方式

  • > HTTP 常見 Content-Type

    > application/x-www-form-urlencoded
    > multipart/form-data
    > application/json

  • > $_POST 預設只能接收到 Content-Type: application/x-www-form-urlencoded 的資料

  • > 如果Content-Type: application/json 需要用到php://input 處理輸入流

    > 請求內容 {"account": "123456"}
    > $tmpData = strval(file_get_contents("php://input"));
    > $DataArray = json_decode($tmpData, true);
    > $account = $DataArray['account'];

  • > Content-Type: multipart/form-data

    > $tmpData = strval(file_get_contents("php://input"));
    > public function parseData($data) {
    > $list = explode("\r\n", $data);
    > foreach($list as $value) {
    > if($value) {
    > if(strstr($value, '--')) continue;
    > if(strpos($value, '-')) {
    > $key = str_replace('"', '', strchr($value, '"'));
    > continue;
    > };
    > if($value) {
    > $array[$key] = $value;
    > }
    > }
    > }
    > return $array;
    > }
    > $DataArray = $this->parseData($tmpData);
    > $DataArray['account'];