Search code examples
javascriptphpxmlhttprequest

Cannot parse a `Content-Disposition: form-data` payload using PHP


I've already read many posts about this topic but it looks like that none of them relate to my context.

I have a JS library which sends to the backend a POST request containing data formatted this way:

------WebKitFormBoundaryDjoP6y6CoTH58A26
Content-Disposition: form-data; name="data"

[{ <JSON formatted data> }}]
------WebKitFormBoundaryDjoP6y6CoTH58A26--

I know because I've used the browser inspector. My problem is that I cannot make to get this data. The conventional file_get_contents('php://input') returns an empty string. Trying to investigate further with apache_request_headers() thist is what the backend reveives:

Array
(
    [Cookie] => PHPSESSID=e8tlf5aocqmb5eu2qliu7pnkl4; arpadmin=s1pg7pg31kl2e9sj96kg2arqc4; __gsas=ID=6ed6b402c3253656:T=1702304073:RT=1702304073:S=ALNI_Mbb4fbtcgyhQiVS58b1D5bl7hnPmA
    [Accept-Language] => en-US,en;q=0.9,it;q=0.8
    [Accept-Encoding] => gzip, deflate
    [Referer] => http://myhostname.mydomain.org/arp/lat.php?mese=1&anno=2024
    [Origin] => http://myhostname.mydomain.org
    [Content-Type] => multipart/form-data; boundary=----WebKitFormBoundaryEAp4qyLXkJs3nO4a
    [User-Agent] => Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0
    [X-Requested-With] => XMLHttpRequest
    [Dnt] => 1
    [Cache-Control] => no-cache
    [Pragma] => no-cache
    [Accept] => application/json
    [Content-Length] => 368
    [Connection] => keep-alive
    [Host] => myhostname.mydomain.org
)

Where are my data?


Solution

  • The most straightforward way to submit JSON to an API end-point is to use Content-Type: application/json, which requires reading raw data from php://input and parsing it yourself. But your JavaScript library is not using that. It's using one of the two classical formats supported by HTML forms, which PHP will automagically decode into $_POST:

    • application/x-www-form-urlencoded
    • multipart/form-data <-- This is yours

    Your raw JSON will be available at $_POST['data'] and applying json_decode() on that should get the expected data... unless the request is something else like PATCH or PUT (inspect $_SERVER['REQUEST_METHOD'] if unsure).