开发者

PHP cURL: upload file from form to remote API?

开发者 https://www.devze.com 2023-03-14 06:07 出处:网络
I\'m trying to upload a file on a form on my site, and then pass it on to a remote API. This is my PHP:

I'm trying to upload a file on a form on my site, and then pass it on to a remote API.

This is my PHP:

$fields = array(
    'file'=>$_FILES["mediaupload"],
    'username'=>urlencode($_POST["u开发者_如何学运维sername"]),
    'password'=>urlencode($_POST["password"]),
    'latitude'=>urlencode($_POST["latitude"]),
    'longitude'=>urlencode($_POST["longitude"]),
);
$fields_string = http_build_query($fields);
$url = my_url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec ($ch);

At the moment I keep getting error messages that the file could not be processed properly. The API expects all fields as POST strings except the file, which it expects in binary.

I know it's going to be tough to debug this for you guys without access to the remote API, but am I doing anything obviously wrong, or should this work?

Many thanks.


File upload using curl does not work like this. You need to first save the file locally using php's move_uploaded_file then get the path to file. In the fields add this,

$fields = array(
    'file'=>"@/path/to/myfile.ext",
    'username'=>urlencode($_POST["username"]),
    'password'=>urlencode($_POST["password"]),
    'latitude'=>urlencode($_POST["latitude"]),
    'longitude'=>urlencode($_POST["longitude"]),
);

Also, I'm not sure if fields array needs to be converted to string to be used as postfields. According to manual it can be an array() directly.

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, files thats passed to this option with the @ prefix must be in array form to work.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号