微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PHP多表单数据PUT请求?

我正在编写一个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头.

原文地址:https://www.jb51.cc/php/132109.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐