
本文详解如何使用 PHP cURL 正确提交包含文件上传及重复键名数组(如 colours[])的 multipart/form-data 请求,解决 Array to string conversion 和 415 Unsupported Media Type 常见错误。
本文详解如何使用 php curl 正确提交包含文件上传及重复键名数组(如 `colours[]`)的 multipart/form-data 请求,解决 `array to string conversion` 和 `415 unsupported media type` 常见错误。
在 PHP 中通过 cURL 模拟类似 curl -F 的表单提交时,若需同时上传文件并传递数组字段(例如 colours[]="red"、colours[]="yellow"),必须严格遵循 multipart/form-data 的字段命名规范。PHP 的 CURLOPT_POSTFIELDS 接收数组时会自动设置正确的 Content-Type: multipart/form-data,但不能直接传入嵌套数组(如 'colours' => ['red','yellow','blue'])——这会导致 Array to string conversion 错误,因为 cURL 无法序列化多维数组为合法的 multipart 字段。
正确做法是将数组元素展开为带数字索引的扁平键名,即显式声明为 'colours[0]'、colours[1]、colours[2]。这与命令行 curl -F 中的 colours[]= 语义等价,服务端(如 PHP-FPM 或大多数 Web 框架)会自动将其解析为 $_POST['colours'] = ['red','yellow','blue']。
以下是完整、可运行的示例代码:
$url = 'https://the.url.com/upload';
$file = '/path/to/the/file';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 获取响应内容
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'file' => curl_file_create($file), // PHP 5.5+,注意路径必须存在且可读
'colours[0]' => 'red',
'colours[1]' => 'yellow',
'colours[2]' => 'blue',
]);
// 可选:显式设置 User-Agent 避免部分服务端拦截
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-cURL');
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200) {
echo "上传成功\n";
} else {
echo "请求失败,HTTP 状态码:{$httpCode}\n";
var_dump($response);
}
⚠️ 关键注意事项:
- curl_file_create() 是 PHP 5.5+ 的标准方式,切勿使用 '@/path' 语法(已废弃且在 PHP 7.4+ 中被禁用);
- 所有数组字段必须展开为独立键值对,键名格式为 name[index](如 colours[0]),而非 name[] 或嵌套数组;
- 不要对 CURLOPT_POSTFIELDS 使用 http_build_query(),否则会退化为 application/x-www-form-urlencoded,导致服务端返回 415 Unsupported Media Type;
- 确保上传文件路径真实存在且具有读取权限,否则 curl_file_create() 将静默失败;
- 如需上传多个文件,可按相同逻辑添加 'files[0]' => curl_file_create($f1), 'files[1]' => curl_file_create($f2) 等字段。
此方案完全兼容标准 PHP 后端(如 $_FILES 和 $_POST 自动解析)、Laravel、Symfony 等主流框架,是生产环境中安全、可靠、符合 RFC 规范的实现方式。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











