Blogging since 2008 until 2010

Getting raw POST data with PHP

John McLear asked me to come over and help him out with some XML-RPC stuff he was working on last week, and the question of how to get raw POST data with PHP came up. I didn't know off the top of my head, and it took a little while to figure / find out, so I thought I would share.

In the old days (oh what dark days they were), there was a special variable you could use to get the raw POST data: $HTTP_RAW_POST_DATA. In these modern times, PHP's input and output streams (you know, the php:// ones) provide the handy-dandy php://input stream, just for getting the raw POST data. The input streams can be passed to a bunch of different functions, but the easiest to use is probably file_get_contents.

I think this little snippet demonstrates nicely:

echo file_get_contents('php://input');
<form action="#" method="post">
  <input type="text" name="textOne" value="Foo"/>
  <input type="text" name="textTwo" value="Bar"/>
  <input type="submit" value="Submit"/>

Pop that into a PHP file on your webserver, view it, hit the Submit button and you should see something a little like this displayed before the form:


Oh look! It's raw POST data! :-)

But, what is it good for? I admit, this kind of thing is of limited use in most people's day to day work, but if you've got XML being fired in a POST request at your script, you don't really have much of an alternative.

First posted: Sun, 27 Jun 2010 22:09:52 +0000