posting a file (HTTP POST request) using curl
Curl works fine when uploading a binary file to a webservice, as long as you're using a HTTP PUT request. When you switch to HTTP POST, curl seems intent on making your life miserable.
Where a PUT request allows you to freely send the file as the request body, POST coerces the file in a multipart/form-data structure. The PHP layer makes this explicit by only allowing the CURLOPT_POSTFIELDS option for indicating which file needs to be uploaded.
For a PUT request, you can use:
A POST request requires you to use:
Sources:
* http://w-shadow.com/blog/2007/10/08/how-to-really-upload-files-with-php/ : explains how to use CURLOPT_POSTFIELDS when POSTing a file.
* http://curl.haxx.se/mail/curlphp-2007-12/0033.html : explains the problem in more detail
* http://bugs.php.net/bug.php?id=46696 : bugfix but for what? As far as I'm seeing, the file is still being sent as multipart/form-data, but with a different Content-Type header.
* http://curl.haxx.se/docs/faq.html#How_do_I_POST_with_a_different_C : same here, you can change the header, but not the body. Thanks a lot curl.
Where a PUT request allows you to freely send the file as the request body, POST coerces the file in a multipart/form-data structure. The PHP layer makes this explicit by only allowing the CURLOPT_POSTFIELDS option for indicating which file needs to be uploaded.
For a PUT request, you can use:
curl_setopt($ch,CURLOPT_INFILE,fopen($filepath,'rb'));
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($filepath));A POST request requires you to use:
curl_setopt($ch,CURLOPT_POSTFIELDS, array('file' => "@$filepath"));
which will automatically pack the file content into a multipart/form-data structure.Sources:
* http://w-shadow.com/blog/2007/10/08/how-to-really-upload-files-with-php/ : explains how to use CURLOPT_POSTFIELDS when POSTing a file.
* http://curl.haxx.se/mail/curlphp-2007-12/0033.html : explains the problem in more detail
* http://bugs.php.net/bug.php?id=46696 : bugfix but for what? As far as I'm seeing, the file is still being sent as multipart/form-data, but with a different Content-Type header.
* http://curl.haxx.se/docs/faq.html#How_do_I_POST_with_a_different_C : same here, you can change the header, but not the body. Thanks a lot curl.
Comments