简体   繁体   中英

Sending multipart/form-data via cURL

I have the following HTML form:

<form enctype="multipart/form-data" id="upload_form" role="region" action="remoteUpload2.php?command=FileUpload&amp;type=Files&amp;currentFolder=%2F&amp;langCode=en&amp;hash=8e402b8b9927640d&amp;" method="POST" target="ckf_19">
<input name="upload" type="file">
<input value="Upload Selected File" type="submit">
<input name="cancel" value="Cancel" type="button">
</form>

When I submit it, if I do a print_r($_FILES) I get the following output:

Array
(
    [upload] => Array
        (
            [name] => logo.png
            [type] => image/png
            [tmp_name] => /tmp/phpvIFI0K
            [error] => 0
            [size] => 12201
        )

)

What I am trying to figure out is how to send a file the same way, using only PHP, to connect two different systems together. I can modify the sending script, but not the receiving script, so I need to send data in the format that is expected.

Is there a way using cURL for me to post data to this script that will result in similar output for $_FILES? I have the file I want to send on the server, I just need to figure out how to POST it to the receiving script.

I was able to solve this problem with the following code:

// initialise the curl request
$request = curl_init('http://www.example.com/connector.php');

// send a file
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_SAFE_UPLOAD, false);
curl_setopt(
    $request,
    CURLOPT_POSTFIELDS,
    array(
      'file' => '@' . realpath('logo.png') . ';filename=logo-test.png'. ';type=image/png'
    ));

// output the response
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);

if(curl_exec($request) === false)
{
    echo 'Curl error: ' . curl_error($ch)."<br>";
}
else
{
    echo 'Operation completed without any errors<br>';
}

// close the session
curl_close($request);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM