Parsing PUT requests in PHP

I’m working on the next generation data access layer for Digg right now, which is basically a REST layer built on top of a partitioned and multihomed database setup. The general idea is that we’ll send GET, POST, PUT and DELETE requests to URI’s on our services layer to access and manipulate data. PHP makes accessing GET and POST easy via $_GET and $_POST. DELETE isn’t an issue since what we’re deleting is just the entity defined by the URI (e.g. Sending DELETE to /2.0/User/1234.xml will delete User 1234).

After a few days work I can create, fetch and delete entities from this setup. Today I started working on implementing the PUT method. I always knew PHP wasn’t exactly top notch when it came to PUT support, but I had no idea how annoying it would be to find a simple solution for parsing PUT information. After some digging around this is what I’ve figured out.

$put = array();
parse_str(file_get_contents('php://input'), $put);

That should parse everything into a native PHP array, including arguments like foo[bar]=1&foo[baz]=2. If anyone knows of a more native way of doing this please let me know.

6 thoughts on “Parsing PUT requests in PHP

  1. Joe, I’m curious as to how you are securing these services to make sure requests are only coming from the places you think it is.

  2. I did notice that PECL extension, but, alas, it also returns a string. I’d still have to use parse_str() to import the data. Additionally, the method I’ve outlined doesn’t require loading another module.

  3. This is defiantly something that needs to be addressed in future versions of PHP. Works for me, though. Thanks!

  4. Joe, working on a RESTful service as well, and this is the only way I could dig up to parse PUT requests (also works for DELETE if you ever need to send body for some odd reason). One thing I’ve done that might make life a bit easier in some cases is to use JSON to chuck the data around, but you still end up having to do some goofy stuff to get the string sanitized so it can be properly json_encoded / decoded.

    Separately, it gets even goofier when you need to make PUT requests in your code, as you need to stream the data into memory before you can curl it, as curl PUTs only accept files… definitely need some better native support for REST in php.

Leave a Reply

