本文介绍了多部分/表单数据进入数组未处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基本上,我有要使用cURL传递的表单数据,这里它被硬编码为边界并仅发送请求.
Basically, I have this form data I'm trying to pass using cURL, here it is hardcoded into boundaries and just sending the request.
$postfields = '--Boundary+0xAbCdEfGbOuNdArY'."\r\n";
$postfields .= 'Content-Disposition: form-data; name="device_timestamp"'."\r\n\r\n";
$postfields .= (time() - (100 * rand(1,6)))."\r\n";
$postfields .= '--Boundary+0xAbCdEfGbOuNdArY'."\r\n";
$postfields .= 'Content-Disposition: form-data; name="photo"; filename="photo"'."\r\n";
$postfields .= 'Content-Type: image/jpeg'."\r\n\r\n";
$postfields .= file_get_contents($path)."\r\n";
$postfields .= '--Boundary+0xAbCdEfGbOuNdArY--'."\r\n";
$result = $this->curl_request('api.com/upload/',$postfields,array(
CURLOPT_HTTPHEADER => array(
'Content-type: multipart/form-data; boundary=Boundary+0xAbCdEfGbOuNdArY',
'Content-Length: '.strlen($postfields),
'Expect:'
)
));
如何将这些数据传递给像这样的函数?
How could I pass this data into a function like so?
private function multipart_build_query($fields){
$retval = '';
foreach($fields as $key => $value){
$retval .= "--".$this->boundary."\r\nContent-Disposition: form-data; name=\"$key\"\r\n\r\n$value\r\n";
}
$retval .= "--".$this->boundary."--";
return $retval;
}
我有点猜测,由于以下几行,我不得不修改我的multipart_build_query
:Content-Type: image/jpeg
I'm kind of guessing I'd have to modify my multipart_build_query
due to the following line : Content-Type: image/jpeg
我尝试执行以下操作
$data_array = array(
"device_timestamp" => (time() - (100 * rand(1,6))),
"photo" => "@".$path,
);
$body = $curl->multipart_build_query($data_array);
仍然无济于事
推荐答案
我建议您制作一个像这样的数组:
I suggest you make an array like this:
$time = (string) (time() - (100 * rand(1,6)));
$photo = file_get_contents($path);
$fields = array(
array(
'headers' => array(
'Content-Disposition' => 'form-data; name="device_timestamp"',
'Content-Length' => strlen($time)
),
'body' => $time
),
array(
'headers' => array(
'Content-Disposition' => 'form-data; name="photo"; filename="photo"',
'Content-Type' => 'image/jpeg',
'Content-Length' => strlen($photo)
),
'body' => $photo
)
);
该方法可以如下所示:
private function multipart_build_query($fields)
{
$data = '';
foreach ($fields as $field) {
// add boundary
$data .= '--' . $this->boundary . "\r\n";
// add headers
foreach ($field['headers'] as $header => $value) {
$data .= $header . ': ' . $value . "\r\n";
}
// add blank line
$data .= "\r\n";
// add body
$data .= $field['body'] . "\r\n";
}
// add closing boundary if there where fields
if ($data) {
$data .= $data .= '--' . $this->boundary . "--\r\n";
}
return $data;
}
您现在有了一种非常通用的方法,它支持任何类型的字段.
You now have a very generic method which supports any kind of field.
这篇关于多部分/表单数据进入数组未处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!