dtcd27183 2016-12-28 08:37
浏览 896

通过cURL发送multipart / form-data

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.

  • 写回答

1条回答 默认 最新

  • dougu1045 2016-12-28 09:42
    关注

    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);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决