1

Is there a way to get PHP to automatically populate the $_POST superglobal array when request bodies are provided as x-www-form-urlencoded or multipart/form-data during a non-post request?

Currently, if I issue a PATCH request with a request body made up of either of the content types above, the data is never entered into a superglobal.

Alexander Trauzzi
  • 7,277
  • 13
  • 68
  • 112
  • 2
    You shouldn't touch superglobals. If the rest of the code needs them. you should write a wrapper around them and have a specific method for populating your wrapper. – Orestes Jul 03 '13 at 15:33
  • I don't need to push the values into superglobals, so that's not a problem. – Alexander Trauzzi Jul 03 '13 at 18:08
  • 1
    No, PHP doesn't have any built-in way to accomplish this; its HTTP abstractions are quite limited and cater to a 1990s version of the web where `GET` and `POST` were the only heavily used HTTP verbs. I've been meaning to write a multiplart MIME parser for a while myself and haven't gotten around to it. PHP, as constituted by its web SAPIs, is not very conducive to RESTful web applications. You can hack together support but at this time the language simply doesn't offer a full (native) HTTP toolkit. –  Jul 03 '13 at 23:18
  • Convert this comment to an answer and I'll mark it correct. – Alexander Trauzzi Jul 05 '13 at 16:40

1 Answers1

3

I ran into a similar problem when building a RESTful API. The following is code which builds $requestData. To Orestes' point, I don't modify superglobals. Should get you started:

switch ($request_method) {
    case 'get':
        $requestData = $_GET;
        break;
    case 'post':
        $requestData = $_POST;
        break;
    case 'put':
    case 'delete':
        // read string from PHP's special input location and parse into an array
        parse_str(file_get_contents('php://input'), $requestData);      
        break;
}
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174