Three Ways to Make a POST Request from PHP
Monday, January 18. 2010
I've been doing a lot of work with services and working with them in various ways from PHP. There are a few different ways to do this, PHP has a curl extension which is useful, and if you can add PECL extensions then pecl_http is a better bet but there are a couple of different ways of using it. This post shows all these side-by-side.
This is pretty straightforward once you get your head around the way the PHP curl extension works, combining various flags with setopt() calls. In this example I've got a variable $xml which holds the XML I have prepared to send - I'm going to post the contents of that to flickr's test method.
$url = 'http://api.flickr.com/services/xmlrpc/';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
First we initialised the connection, then we set some options using setopt(). These tell PHP that we are making a post request, and that we are sending some data with it, supplying the data. The CURLOPT_RETURNTRANSFER flag tells curl to give us the output as the return value of curl_exec rather than outputting it. Then we make the call and close the connection - the result is in $response.
Pecl_Http has two interfaces - one procedural and one object-oriented; we'll start by looking at the former. This is even simpler than in curl, here's the same script translated for pecl_http:
$url = 'http://api.flickr.com/services/xmlrpc/';
$response = http_post_data($url, $xml);
This extension has a method to expressly post a request, and it can optionally accept data to go with it, very simple and easy.
Finally let's see what the OO verison of the extension looks like. Exactly the same call as both the above examples, but using the alternative interface, means our code looks like this:
$url = 'http://api.flickr.com/services/xmlrpc/';
$request = new HTTPRequest($url, HTTP_METH_POST);
$request->setRawPostData($xml);
$request->send();
$response = $request->getResponseBody();
This example is quite a bit longer than the previous one, and you might think this indicates that this approach is more complicated. In some senses that is true and its probably overkill for our extremely trivial example. However it is worth mentioning that the pecl_http extension is extremely flexible and powerful, and can handle some cases that the curl extension can't. So even if it looks more complicated here, it can still be an excellent choice to implement.
That was a very fast round-up of three ways you could make an arbitrary web service call from PHP - hopefully these examples are clear and will help anyone just starting to implement something along these lines.
POSTing from PHP Curl
This is pretty straightforward once you get your head around the way the PHP curl extension works, combining various flags with setopt() calls. In this example I've got a variable $xml which holds the XML I have prepared to send - I'm going to post the contents of that to flickr's test method.
$url = 'http://api.flickr.com/services/xmlrpc/';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
First we initialised the connection, then we set some options using setopt(). These tell PHP that we are making a post request, and that we are sending some data with it, supplying the data. The CURLOPT_RETURNTRANSFER flag tells curl to give us the output as the return value of curl_exec rather than outputting it. Then we make the call and close the connection - the result is in $response.
POSTing from Pecl_Http
Pecl_Http has two interfaces - one procedural and one object-oriented; we'll start by looking at the former. This is even simpler than in curl, here's the same script translated for pecl_http:
$url = 'http://api.flickr.com/services/xmlrpc/';
$response = http_post_data($url, $xml);
This extension has a method to expressly post a request, and it can optionally accept data to go with it, very simple and easy.
POSTing from Pecl_Http: the OO interface
Finally let's see what the OO verison of the extension looks like. Exactly the same call as both the above examples, but using the alternative interface, means our code looks like this:
$url = 'http://api.flickr.com/services/xmlrpc/';
$request = new HTTPRequest($url, HTTP_METH_POST);
$request->setRawPostData($xml);
$request->send();
$response = $request->getResponseBody();
This example is quite a bit longer than the previous one, and you might think this indicates that this approach is more complicated. In some senses that is true and its probably overkill for our extremely trivial example. However it is worth mentioning that the pecl_http extension is extremely flexible and powerful, and can handle some cases that the curl extension can't. So even if it looks more complicated here, it can still be an excellent choice to implement.
In Conclusion
That was a very fast round-up of three ways you could make an arbitrary web service call from PHP - hopefully these examples are clear and will help anyone just starting to implement something along these lines.
Silencing Curl's Progress Output
Tuesday, December 29. 2009
I seem to have been writing a lot of shell scripts to do things with curl lately, and the main difference with piping curl's output to somewhere rather than just looking at it on the screen is that curl will then start outputting a whole bunch of progress information that you don't usually see. This can be frustrating if you wanted the same output as it viewed on the command line, or (as in my case) just wanted to grep for something in the header output.
To silence the additional output, use the -s switch - but be aware that this will also silence any error messages as well! Something like this:
curl -s http://lornajane.net | grep PHP
This will enable you pass into grep just the output you would usually see on your terminal. Hope this is useful to someone!
To silence the additional output, use the -s switch - but be aware that this will also silence any error messages as well! Something like this:
curl -s http://lornajane.net | grep PHP
This will enable you pass into grep just the output you would usually see on your terminal. Hope this is useful to someone!
Cookies and Curl
Monday, December 21. 2009
curl is the C URL library - its a command-line tool for making web requests, with libraries available in many languages. Personally I prefer to use it from the command line and recently I have been using it with cookies for a web services which set a cookie at login and then needed this to be supplied on all subsequent requests. This turned out to be really simple so I thought I'd put some notes down on how to do it.
Quite enchantingly, its traditional to call a cookie storage a "cookie jar" which makes a lot of sense when you think about it! To do this with curl, use the -c switch:
curl -c lj.txt http://www.lornajane.net
If you now examine the resulting file, lj.txt, you'll see that it contains all the details of the cookie. You can edit this if you want to (health warning: only do this if you know what you are doing! If you need to test something though, its useful), and then submit the next request with that cookie attached - exactly as your browser would.
To make the next request with the cookie, simple replace the -c with a -b to dip into the cookie jar and sent all relevant cookies for this domain with your request, like this:
curl -b lj.txt http://www.lornajane.net
As I say, I was using this with a web service, where it made no sense to use a browser as I also needed to pass data with the requests. You might also like to refer to my curl cheat sheet previous post.
Storing Cookies in a Jar
Quite enchantingly, its traditional to call a cookie storage a "cookie jar" which makes a lot of sense when you think about it! To do this with curl, use the -c switch:
curl -c lj.txt http://www.lornajane.net
If you now examine the resulting file, lj.txt, you'll see that it contains all the details of the cookie. You can edit this if you want to (health warning: only do this if you know what you are doing! If you need to test something though, its useful), and then submit the next request with that cookie attached - exactly as your browser would.
Making Requests with Cookies
To make the next request with the cookie, simple replace the -c with a -b to dip into the cookie jar and sent all relevant cookies for this domain with your request, like this:
curl -b lj.txt http://www.lornajane.net
As I say, I was using this with a web service, where it made no sense to use a browser as I also needed to pass data with the requests. You might also like to refer to my curl cheat sheet previous post.
PUTting data fields with PHP cURL
Friday, July 17. 2009
This is a little post about how to PUT multiple data fields using the PHP cURL extension. Why I wanted to do this in the first place is beyond the scope of this post, since its quite a long story. The curl command line allows data fields to be sent with a PUT request, and I wanted to do the same from PHP. Here is a snippet of code to show how I did it.
$data = array("a" => $a);
$ch = curl_init($this->_serviceUrl . $id);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
$response = curl_exec($ch);
if(!$response) {
return false;
}
I'm putting this here so I remember for next time - if it helps you as well then even better :)
$data = array("a" => $a);
$ch = curl_init($this->_serviceUrl . $id);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
$response = curl_exec($ch);
if(!$response) {
return false;
}
I'm putting this here so I remember for next time - if it helps you as well then even better :)
Using curl and PHP to talk to a REST service
Monday, September 15. 2008
Having recently written articles about curl and about writing a PHP REST server, I thought I'd complete the circle and put here a few notes on using PHP's curl wrapper as a Rest client. Also I had to look some of this up when I needed to actually do it so next time I need only look in one place!
If you don't know about PHP, Rest, or curl, then I recommend you do a little reading around each of those subjects before reading this as its unlikely to make much sense - I'm not including background on these topics as there are better resources elsewhere.
I've written about using curl before from the command line, but this example uses PHP's curl to access the service. This is just a simple example, but hopefully if you are doing something along these lines you can adapt for your needs.
In the example, we set the URL we'd like to call and initialise the curl object to point to that. Then we create an array of post data, and configure curl to use POST to make the request and to use our data array.
$service_url = 'http://example.com/rest/user/';
$curl = curl_init($service_url);
$curl_post_data = array(
"user_id" => 42,
"emailaddress" => 'lorna@example.com',
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_response = curl_exec($curl);
curl_close($curl);
$xml = new SimpleXMLElement($curl_response);
We execute the request and capture the response. Health warning: by default curl will echo the response (for reasons that aren't clear to me), if you want to parse it then you will need to use the CURLOPT_RETURNTRANSFER flag to have curl return the response rather than a boolean indication of success - this fooled me completely for a while, I have no idea why it works this way. As you can see I've parsed the resulting XML and my script can then continue with the data it acquired. Depending what you need to do next, you can manipulate the SimpleXMLElement object as you need to.
If you're working with PHP and services, then hopefully this will get you started, if you have any questions or comments, then please add them below!
If you don't know about PHP, Rest, or curl, then I recommend you do a little reading around each of those subjects before reading this as its unlikely to make much sense - I'm not including background on these topics as there are better resources elsewhere.
I've written about using curl before from the command line, but this example uses PHP's curl to access the service. This is just a simple example, but hopefully if you are doing something along these lines you can adapt for your needs.
In the example, we set the URL we'd like to call and initialise the curl object to point to that. Then we create an array of post data, and configure curl to use POST to make the request and to use our data array.
$service_url = 'http://example.com/rest/user/';
$curl = curl_init($service_url);
$curl_post_data = array(
"user_id" => 42,
"emailaddress" => 'lorna@example.com',
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_response = curl_exec($curl);
curl_close($curl);
$xml = new SimpleXMLElement($curl_response);
We execute the request and capture the response. Health warning: by default curl will echo the response (for reasons that aren't clear to me), if you want to parse it then you will need to use the CURLOPT_RETURNTRANSFER flag to have curl return the response rather than a boolean indication of success - this fooled me completely for a while, I have no idea why it works this way. As you can see I've parsed the resulting XML and my script can then continue with the data it acquired. Depending what you need to do next, you can manipulate the SimpleXMLElement object as you need to.
If you're working with PHP and services, then hopefully this will get you started, if you have any questions or comments, then please add them below!
Curl Cheat Sheet
Tuesday, August 19. 2008
I have a scribbled sheet on my desk, which is my "cheat sheet" for curl, its really short and I thought I'd put my notes here for safe-keeping. If you're visiting, then I hope they help you too.
Curl is a way of making web requests from the command line. I only do this under linux, and if you don't know why you'd want to do that, then you probably don't need to read any further (although, that would also make an interesting article!).
curl http://www.lornajane.net
Will give you the output that would be sent to your browser if you requested the main page of this site from there.
This is where it gets interesting, you can see the actual information being included with the HTTP request when you use the verbose switch.
curl -v http://www.lornajane.net
Try it - you see the headers and the client/server negotiation. Stuff like cache information, browser identification, and cookie information all gets transmitted in these headers.
Curl can make requests and include data with them. It can use GET as you'd expect, but POST, PUT and DELETE are all supported too.
curl -X GET "http://www.example.com?page=2&category=toys"
I've added the quotes because the ampersand confuses the command line
curl -X POST http://www.example.com/registration.php -d username=lornajane -d password=password -d phone=0123456789
PUT and DELETE can be done in the same way, just using the -X switch.
Actually, if you've got this far then you know what you're doing - use the curl manpage for information on the other switches. Curl can do more things than I think I would ever want to do, not just HTTP, and can spoof cookies and all sorts of other good things. Its especially good for testing web services as it allows clearer diagnosis of the exact behaviour and response. Don't tell anyone but I have also been known to vardump in the middle of webservices when debugging, and using curl lets you see the output "as it comes" - very handy!
Curl from command line
Curl is a way of making web requests from the command line. I only do this under linux, and if you don't know why you'd want to do that, then you probably don't need to read any further (although, that would also make an interesting article!).
curl http://www.lornajane.net
Will give you the output that would be sent to your browser if you requested the main page of this site from there.
Verbose output (-v)
This is where it gets interesting, you can see the actual information being included with the HTTP request when you use the verbose switch.
curl -v http://www.lornajane.net
Try it - you see the headers and the client/server negotiation. Stuff like cache information, browser identification, and cookie information all gets transmitted in these headers.
Using HTTP verbs (-X) and data (-d)
Curl can make requests and include data with them. It can use GET as you'd expect, but POST, PUT and DELETE are all supported too.
curl -X GET "http://www.example.com?page=2&category=toys"
I've added the quotes because the ampersand confuses the command line
curl -X POST http://www.example.com/registration.php -d username=lornajane -d password=password -d phone=0123456789
PUT and DELETE can be done in the same way, just using the -X switch.
Further Resources
Actually, if you've got this far then you know what you're doing - use the curl manpage for information on the other switches. Curl can do more things than I think I would ever want to do, not just HTTP, and can spoof cookies and all sorts of other good things. Its especially good for testing web services as it allows clearer diagnosis of the exact behaviour and response. Don't tell anyone but I have also been known to vardump in the middle of webservices when debugging, and using curl lets you see the output "as it comes" - very handy!
(Page 1 of 1, totaling 6 entries)



Comments