用PHP curl发布文件数组

时间:2018-11-09 11:47:29

标签: php curl http-post multipartform-data php-curl

我想使用PHP和curl将文件数组发布到服务器。在HTML中,其外观如下:

<form method="POST" type="multipart/form-data">
    <input type="text" name="fieldx" value="123"/>
    <input type="file" name="localfile[]"/>
    <input type="file" name="localfile[]"/>
</form>

对于CURL也应这样做:

$postParameters['fieldx'] = "123";
$postParameters['localfile'] = array("fulllocalfilepath1", "fulllocalfilepath2");

$request = curl_init('http://server.abc');
curl_setopt($request, CURLOPT_POST, true);
curl_setopt(
    $request,
    CURLOPT_POSTFIELDS,
    $postParameters
);  
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
$rawData = curl_exec($request);
curl_close($request);

但是使用CURL时服务器没有收到localfile数组。发送文件的正确命令是什么?

此致

1 个答案:

答案 0 :(得分:0)

得到解决方案:

$postParameters['fieldx'] = "123";
$postParameters['localfile[0]'] = new cURLFile("fulllocalfilepath1", "mime", "readable name 1");
$postParameters['localfile[1]'] = new cURLFile("fulllocalfilepath2", "mime", "readable name 2");
$request = curl_init('http://server.abc');
curl_setopt($request, CURLOPT_POST, true);
curl_setopt(
    $request,
    CURLOPT_POSTFIELDS,
    $postParameters
);  
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
$rawData = curl_exec($request);
curl_close($request);