Posting multipart form data using PHP

@shvi asked me for this code over Twitter, I though it would a good idea to share it here.

The following code is used to post two different fields, a simple text data named “somedata” and a file named “somefile”.
Hope it helps :)

echo adrotate_group(4);

15 thoughts on “Posting multipart form data using PHP

  1. Yoan

    Wasn’t he looking for a SOAP client that supports that lovely spec: and the offical SOAP implementation of PHP doesn’t support it:

    He sits on the other side of the POST.

    It’s not a big deal to add this imho,


    P.S.: I’m sure you would enjoy using the <<< notation instead of doing so many repetitive concatenations.

  2. Andrew Glowik

    Thank you much for this exposition of code. I was at an impasse with PHP/curl using GlassFish/Quercus with a multipart/form-data post. Using your example to build my own form unwwedged me!

  3. Afanasy Kurakin

    Thanks for the great snippet, it still helps!

    Please note, that semicolon after $params is missing, plus in my case, when handling upload with php I’ve removed base64 encoding because php couldn’t understand it and kept data encoded.

  4. Jason

    Dude! You’re the one and only salvation through this nightmare of mine. I struggled hectically trying to find a way to parse a normal text field with my file upload through a multipart/form-data form

    Thanks a stash


  5. Albi Patozi

    Hey For the solution Thanks it was great, but i have a question : WHY DOESNT IT WORK ONLINE BUT ONLY ON LOCALHOST ?! what shold i try to change ? thanks in advice

      1. Albi Patozi

        hmm that seems that file_get_contents does not send the $ctx- context. maybe its problem of the php version. have you ever tested it in php 5.2.* ? (by the way, im vary thankful for your reply)

        1. Claude

          nope, tested on 5.3 only, but there’s no indication it shouldn’t be working with 5.2

          you should be posting your code on StackOverflow and post the link here

          1. albi patozi

            Thanks a lot. i have posted the question there but nobody answered. hehe . it doesnt metter now i have found another solution without post .

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.