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 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导
  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp