前端之家收集整理的这篇文章主要介绍了
PHP多表单数据PUT请求?,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_
502_0@
我正在编写一个RESTful API.我使用不同的动词
上传图像时遇到麻烦.
考虑:
我有一个可以通过post / put / delete / get请求创建/修改/删除/查看URL的对象.当有要上传的文件时,请求是多部分表单,或者只有文本处理时,应用程序/ xml.
要处理与对象相关联的图像上传,我正在做如下事情:
if(isset($_FILES['userfile'])) {
$data = $this->image_model->upload_image();
if($data['error']){
$this->response(array('error' => $error['error']));
}
$xml_data = (array)simplexml_load_string( urldecode($_POST['xml']) );
$object = (array)$xml_data['object'];
} else {
$object = $this->body('object');
}
这里的主要问题是在尝试处理put请求时,显然$_POST不包含put数据(据我所知)!
作为参考,这是我如何构建请求:
curl -F userfile=@./image.png -F xml="<xml><object>stuff to edit</object></xml>"
http://example.com/object -X PUT
有没有人有任何想法,我如何可以访问我的PUT请求中的xml变量?
首先,处理PUT请求时,$_FILES不会被填充.在处理POST请求时,它仅由
PHP填充.
您需要手动解析.这也适用于“常规”领域:
// Fetch content and determine boundary
$raw_data = file_get_contents('PHP://input');
$boundary = substr($raw_data,strpos($raw_data,"\r\n"));
// Fetch each part
$parts = array_slice(explode($boundary,$raw_data),1);
$data = array();
foreach ($parts as $part) {
// If this is the last part,break
if ($part == "--\r\n") break;
// Separate content from headers
$part = ltrim($part,"\r\n");
list($raw_headers,$body) = explode("\r\n\r\n",$part,2);
// Parse the headers list
$raw_headers = explode("\r\n",$raw_headers);
$headers = array();
foreach ($raw_headers as $header) {
list($name,$value) = explode(':',$header);
$headers[strtolower($name)] = ltrim($value,' ');
}
// Parse the Content-Disposition to get the field name,etc.
if (isset($headers['content-disposition'])) {
$filename = null;
preg_match(
'/^(.+); *name="([^"]+)"(; *filename="([^"]+)")?/',$headers['content-disposition'],$matches
);
list(,$type,$name) = $matches;
isset($matches[4]) and $filename = $matches[4];
// handle your fields here
switch ($name) {
// this is a file upload
case 'userfile':
file_put_contents($filename,$body);
break;
// default for all other files is to populate $data
default:
$data[$name] = substr($body,strlen($body) - 2);
break;
}
}
}
在每次迭代时,$data数组将用你的参数填充,$headers数组将用每个部分的头部填充(例如:Content-Type等),$filename将包含原来的文件名,if在请求中提供并适用于该领域.
请注意,以上内容仅适用于多部分内容类型.确保在使用上述内容来解析主体之前检查请求Content-Type头.