NYCPHP Meetup

NYPHP.org

[nycphp-talk] I am about to pull my hair out over file uploads with cURL. Help!

Rob Marscher rmarscher at beaffinitive.com
Wed Feb 16 10:08:26 EST 2011


On Feb 16, 2011, at 5:29 AM, Werner wrote:
>> You mention that
>> The final variable (media) should contain the binary data of the file
>> In that case, the following code might be what one would expect to use?
>> 
>> $post = array(
>>    'cmd' => 'uploadmessage',
>>    'session' => $_SESSION[sid], // No need for double quotes
>>    'message_guid' => $msg_guid, // No need for double quotes
>>    'file_name' => "$file_name.mov",
>>    'media' => file_get_contents($target_path) // Assigning the binary
>> file data
>> );

On Feb 16, 2011, at 6:03 AM, Anthony Papillion wrote:
> You're very right. THAT code seems to work with no problem at all. Well,
> there *is* a problem, but I think it's on the server side as it seems to
> think that there is no 'cmd' variable being passed. Yet, when I
> print_r($post) I can clearly see that 'cmd' is being passed. Weird.  But
> anyway, YOUR code does indeed work! Thank you for the corrections!

Using the @ sign is the proper way to upload a file via curl in php.  But it's possible that the API is expecting the data differently than how that works (or perhaps there's an issue with the path contained in $target_path).  I think you need this to be an absolute path on the file system rather than relative to where your script is running.

From php.net:
CURLOPT_POSTFIELDS	The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set tomultipart/form-data. As of PHP 5.2.0, files thats passed to this option with the @ prefix must be in array form to work.


The server returning that 'cmd' wasn't passed is strange.

Did you try setting verbose to true?  It should output debug info to your error log (or output on command line if you're running it that way).
curl_setopt($ch, CURLOPT_VERBOSE, true);

Maybe also add follow location in case the server does some type of redirect?
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

Is HTTPS involved?




More information about the talk mailing list