Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LibCURL sends filename rather than file contents when I try to upload a binary file in Windows Server 2008

I'm getting this weird behavior with libCURL. When I try to upload a file by appending "@" to the beginning of filename (as documented in libCURL's man page), instead of file contents being uploaded, libCURL sends the filename itself (with the @ in the beginning).

This is running on Windows 2008 R2, with xampp version 5.6.8, which has curl compiled in (curl version 7.40.0).

Here's releant code fragment:

$post['pic'] = "@C:\\image.png";

$ret = curl_setopt( $ch, CURLOPT_POST, TRUE );
if (!$ret) die("curl_setopt CURLOPT_POST failed");
$ret = curl_setopt( $ch, CURLOPT_POSTFIELDS, $post );
if (!$ret) die("curl_setopt CURLOPT_POSTFIELDS failed");

$response = curl_exec( $ch );

This code works on Linux but not Windows Server 2008.

Here's the form data that I get:

Content-Type: multipart/form-data; \\
boundary=------------------------c74a6af8b52d997a

--------------------------c74a6af8b52d997a
Content-Disposition: form-data; name="pic"

@C:\image.png
--------------------------c74a6af8b52d997a--

As you can see I receive @C:\image.png rather than contents.

Does anyone know why libCURL wouldn't upload the file contents?

like image 848
bodacydo Avatar asked Jul 30 '15 19:07

bodacydo


1 Answers

From the documentation of curl-setopt

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 to multipart/form-data. As of PHP 5.2.0, value must be an array if files are passed to this option with the @ prefix. As of PHP 5.5.0, the @ prefix is deprecated and files can be sent using CURLFile. The @ prefix can be disabled for safe passing of values beginning with @ by setting the CURLOPT_SAFE_UPLOAD option to TRUE.

The behavior depends on php release and @ prefix is now deprecated.

You should use CurlFile class to set the CURLOPT_POSTFIELDS of the curl request like this :

$post['pic'] = new CurlFile('C:\\image.png');
$ret = curl_setopt( $ch, CURLOPT_POSTFIELDS, $post );
like image 135
mpromonet Avatar answered Nov 07 '22 22:11

mpromonet