问题描述
我在使用PHP和CURL上传文件时无法发布多维数组。
I'm having problems with posting a multidimensional array with file uploads using PHP and CURL.
多维数组例如:
$post['question'] = 'Are you human?';
$post['answers'] = array('yes', 'no', 'maybe');
$post['file'] = '@/path/to/file';
// Output:
Array(
'question' => Are you human?,
'answers' => Array(
'0' => yes,
'1' => no,
'2' => maybe
),
'file' => @/path/to/file
)
如果你只是试图发布这个CURLOPT_POSTFIELDS在CURL像这样:
There are a few things why this wouldn't work if you simply try to post this with CURLOPT_POSTFIELDS in CURL like this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
首先是官方PHP 说:
First of all the official PHP description of CURLOPT_POSTFIELDS says:
这听起来像你可以传递任何类型的数组到POSTFIELDS对吧?错误。 POSTFIELDS只接受非标量值,并且在传递多维数组时会遇到数组到字符串转换
错误。所以,你唯一的另一个选择是 http_build_query()
你的数组能够传递不阻塞的多维数组。
It sounds like you can pass any kind of array to POSTFIELDS right? Wrong. POSTFIELDS only accepts non-scalar values and will choke with a Array to string conversion
error when passing on multi-dimensional arrays. So, the only other option you have is to http_build_query()
your array to be able to pass multidimensional arrays that don't choke.
但您可以在PHP页面的注释中阅读:
But.. as you can read in the note on the PHP page:
如果您通过urlencoded字符串到POSTFIELDS,导致你的文件上传失败。
The post will not be multipart/form-data encoded if you pass an urlencoded string to POSTFIELDS, causing your file upload to fail.
因此,似乎几乎不可能结合两个与CURL,而不会是一个问题,如果你' d使用一个常规的HTML表单。
So it seems nearly impossible to combine the two with CURL, while it wouldn't be a problem if you'd used a regular HTML form.
我的问题是:是否有可能绕过这个奇怪的奇怪的CURL,以便能够发布多维数组和文件上传?
My question is: is it possible to bypass this weird quirk of CURL to be able to post multidimensional arrays and file uploads?
推荐答案
multipart / form-data不支持嵌套值。我不相信CURL可以做到这一点。
multipart/form-data doesn't support nested values. And I don't believe CURL can do it either.
我怀疑你的请求的接收端也是一个PHP脚本。如果,你可以提交一个嵌套数组作为值之一,如果你只是自己准备:
I suspect the receiving end of your request is also a PHP script. If, then you can submit a nested array as one of the values, if you just prepare it yourself:
$post['answers[0]'] = "yes";
$post['answers[1]'] = "no";
$post['answers[2]'] = "maybe";
理论上,你只需要'answers []'
没有索引,但是会覆盖前面的值 - 因此只能使用http_build_query。
Theoretically you'd just need 'answers[]'
without the index, but that would overwrite the preceeding value - and thus only works with http_build_query.
我不确定在PHP中是否有任何HTTP库这可以自动执行此操作。
I'm not sure if there is any HTTP library in PHP which can do this automatically.
这篇关于如何使用PHP和CURL上传多维POSTFIELDS文件(multipart / form-data)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!