How to parse multipart data manually in PHP when working with HTTP PUT requests.
Luckily, PHP offers some great tools for working with data that we usually take for granted. When posting multipart form-data to a PHP script, the POST values will automatically become available as an array of values in the $_POST superglobal, the files will automatically be processed and be made available in the $_FILES superglobal. Unfortunately, this doesn’t work for PUT requests. This is probably by design, as with a PUT request you are actually sending a specific file to a specific location on a server. This is supported, as is sending an url-encoded querystring as the payload. What doesn’t work out of the box though is sending multipart data in a PUT request.
Consider the following pseudo code on the client side:
If you get rid of the CURLOPT_CUSTOMREQUEST bit, this will be sent as a POST, and the data will be available in the $_POST and $_FILES arrays respectively. With PUT, the data will not be parsed by PHP at all. So I wrote a method to do it manually. Unparsed multipart data looks something like this:
Here’s a method that will parse this:
And here’s how to use it:
In the above example, the var_dump would look something like this:
I hope this helps.
I’m happy to see that a few people have used the code above and some have changed it to meet their requirements. Check out commenter Jas’ version for multiple file and input-type support.