PHP “php://input” vs $_POST

前端 未结 6 1928
离开以前
离开以前 2020-11-21 23:55

I have been directed to use the method php://input instead of $_POST when interacting with Ajax requests from JQuery. What I do not understand is t

6条回答
  •  一生所求
    2020-11-22 00:15

    php://input can give you the raw bytes of the data. This is useful if the POSTed data is a JSON encoded structure, which is often the case for an AJAX POST request.

    Here's a function to do just that:

      /**
       * Returns the JSON encoded POST data, if any, as an object.
       * 
       * @return Object|null
       */
      private function retrieveJsonPostData()
      {
        // get the raw POST data
        $rawData = file_get_contents("php://input");
    
        // this returns null if not valid json
        return json_decode($rawData);
      }
    

    The $_POST array is more useful when you're handling key-value data from a form, submitted by a traditional POST. This only works if the POSTed data is in a recognised format, usually application/x-www-form-urlencoded (see http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4 for details).

提交回复
热议问题