Sticky Posts
Jun 1, 2009
MultiPart Form Encoding In PHP | POST File Uploads
HTML Forms & Multipart
With POST operations, 99% of the times the data is application/x-www-form-urlencoded which is the format you get from http_build_query. But, when you upload files (large data) you need multipart forms which are built for the big items. So, to upload files using HTML forms, you need to add enctype="multipart/form-data" to your form and use input="file" inputs.
To achieve this with cURL you need to set the file POSTFIELDS like this field => @file_path. But I never enjoy letting others encode my own shit. So I needed to take control here and create a function that can Multipart Encode to a string or a local file. Outputing to a string is good for small data but outputing to a file is good for large data that should not be handled in memory. As cURL accepts INFILE and INFILESIZE for the likes of POSTs and PUTs to send data from a file (not from memory) we can combine the two functions and make file uploads dead easy.
The next few lines will detail the encoding and later on I will publish my new cURL wrapper that is designed to upload / download large files and so on.
The Actual Script
See below the script doing the magic. It has 4-5 different function names doing same thing but I like to do this a lot. I get all those intuitive function names and easily remember them when writing code.
It uses el_files_getMIME if exists. Otherwise Content-Type is not added to encoded files.
Registration is quick, painless and worth its weight in gold.
You can use like this to encode to a file. It returns the file path to the encoded data.
$post = array('note' => 'note1', 'upfile' => __FILE__);
$mp_file = el_http_mpEncode($post, $ctype, dirname(__FILE__).'/mpencoded.txt');
//$ctype returns the Content-Type you need to use
Or like this to encode to a string in memory. It returns ... a string.
$post = array('note' => 'note1', 'upfile' => __FILE__);
$mp_data = el_http_mpEncode($post, $ctype);
//$ctype returns the Content-Type you need to use
Very easy to use. If you add a filename as last parameter, you write everything to a file. Otherwise it returns encoded data as a string.
Testing It
Try it POSTing to http://cgi-lib.berkeley.edu/ex/fup.cgi from http://cgi-lib.berkeley.edu/ex/fup.html. The above array is created for this very FORM.


Wow, great script, just what I was looking for. Thank you very much!
This is exact code i was looking in PHP, now my PHP problem is solved. Now i am searching for same code in C#. I will try to convert it, if you have same code in C# could you please post it or give me link.
Thanks,
Suresh
I don’t do C# only C++. But … with some basic C# knowledge it should not be difficult to convert.