a notice

How To Build A multipart/form-data POST request

Need to create a POST request that uploads a file?
I spent this afternoon trying to figure out what one looks like. This document includes a template that has been successful for me.


========================
POST /path/to/script.php HTTP/1.0
Host: example.com
Content-type: multipart/form-data, boundary=AaB03x
Content-Length: $requestlen

--AaB03x
content-disposition: form-data; name="field1"

$field1
--AaB03x
content-disposition: form-data; name="field2"

$field2
--AaB03x
content-disposition: form-data; name="userfile"; filename="$filename"
Content-Type: $mimetype
Content-Transfer-Encoding: binary

$binarydata
--AaB03x--
==========================

Note that you have to generate the Content-Length header after you generate the body of the request (from the first --AaB03x down, including the file data), so the thing to do in practice is to build the body first, get the strlen(), and then build the headers onto the front of the body.

See RFC1867 - Form-based File Upload in HTML (http://www.faqs.org/rfcs/rfc1867.html) for more info on the format of "multipart/form-data" posts.
Good luck!

(As posted to the fsockopen page of the PHP Manual, by me.)

By Chris Snyder on Friday, March 28, 2003

permalink - uplink/email

jump to top