Php curl 发送带有数据的文件

Php Curl send File with data

我需要上传 3 个文件以及 post 数据中的变量。这就是我的电话的样子 -

$data['type1'] = new CurlFile($file1);
$data['type2'] = new CurlFile($file2);
$data['type3'] = new CurlFile($file3);

curl_setopt($ch, CURLOPT_POSTFIELDS, $data, "var1: $val1", "var2: $val2"); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data', "headkey: $headkeyValue"));

我无法从 slim 框架中获取 $app->request()->post('var1');。它是空的。

这是因为所有使用 HTTP POST 方法上传的文件都在 $_FILES 全局变量中。这就是为什么你不能通过这种方式访问​​文件

$app->request()->post('val1');

但您可以使用 $_FILES

$_FILES 描述

An associative array of items uploaded to the current script via the HTTP POST method. The structure of this array is outlined in the POST method uploads section.

这里是 curl 请求示例

$curlFile = curl_file_create($uploaded_file_name_with_full_path);
$post = array('val1' => 'value','val2' => 'value','file_contents'=> $curlFile );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$your_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

别忘了输入合适的 header.
你也可以在这里找到好的资源 Curl File Upload 通过 CURL 发送文件。确保您在上面代码中的 file_contents 键上传递文件。

这是我根据的回答所做的:

$data['type1'] = new CurlFile($file1);
$data['type2'] = new CurlFile($file2);
$data['type3'] = new CurlFile($file3);

//New Code Added
$data['var1'] = "$val1";
$data['var2'] = "$val2";

//removed the trailing string
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);