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条回答 默认 最新

相关推荐 更多相似问题