dongqiao0953 2015-05-31 04:47
浏览 39
已采纳

PHP解析PUT请求

I've spent hours trying to get PHP to parse a PUT request into key/value pairs.

The request is coming out of Ember Data and is of type form-data and I can't change that (Ember Data doesn't allow that as far as I know). I don't want to install a PHP extension (limits my hosting options) or use a PHP framework.

So, using Postman, the request looks like this:

------WebKitFormBoundarytb5fqcjpCsLTsDjp
Content-Disposition: form-data; name="phone_number"

1234567
------WebKitFormBoundarytb5fqcjpCsLTsDjp
Content-Disposition: form-data; name="legal_name"

Drew Baker
------WebKitFormBoundarytb5fqcjpCsLTsDjp
Content-Disposition: form-data; name="first_name"

Drew
------WebKitFormBoundarytb5fqcjpCsLTsDjp
Content-Disposition: form-data; name="last_name"

Baker
------WebKitFormBoundarytb5fqcjpCsLTsDjp--

I have no idea what it would look like from other browsers. I'm assuming it would look different.

Currently the best I could do was this:

$input = file_get_contents('php://input');
$patten = '';
preg_match_all($patten, $input, $matches);

I wasn't able to come up with a patten that was even close. But I think ideally it would search like this:

name=" then everything in between ---

If you guys think that form-data is structured differently on other browsers, maybe there is a better patten to use.

After I got $matches back, I planed on looping through them and merging everything into the $_REQUEST superglobal having all the correct key/value pairs, like so:

$put_vars = array(
   'phone_number'   => '1234567',
   'legal_name'     => 'Drew Baker',
   'first_name'     => 'Drew',
   'last_name'      => 'Baker'
);
$_REQUEST = array_merge($_REQUEST, $put_vars);

My plan is to add this as a high level function in my code, something like parse_put_vars_into_request. But ideally it would work for DELETE and other HTTP methods too.

I understand that regex isn't the ideal way to solve this problem, but given that it needs to work with form-data, it's the best I could think of.

Thanks!

  • 写回答

1条回答 默认 最新

  • douhao2153 2015-06-01 17:14
    关注

    As @zedfoxus pointed out, this is the answer: http://www.chlab.ch/blog/archives/php/manually-parse-raw-http-data-php

    But @steveax suggested just making a custom Ember Data adapter to avoid using PUT's altogether: http://emberjs.com/api/data/classes/DS.Adapter.html#method_updateRecord

    Both are great answers. I think I'll try out the server side solution, because I like the RESTful nature of GET/POST/PUT/DELETE.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀