Making HTTP requests in PHP is not difficult, and a variety of methods exists: using fopen(), using cURL extension, using file streams with fsockopen() and fwrite() for instance. The problem is: depending on server setup, this might or might not work on another server. The good new is: once again, WordPress has a no-brainer API that makes it dead easy and compatible with all environments.
Introducing PHP class WP_Http
WordPress, since version 2.7 and thanks to the extreme coding leetness of Jacob Santos, has a nifty class that sits in your wp-includes directory, in file http.php: WP_Http
The power and beauty of this class is that, depending on what's available on the server, it will pick up the best method to perform HTTP request. Don't bother checking for the presence of HTTP extension, fopen() behavior, existence of curl_init(), as this class will do all this for you.
Basically, all the code you need to type is, more or less:
-
$request = new WP_Http;
-
$result = $request->request( 'http://some.url.you-need.to-fetch' );
Variable $result will be an array, containing the following items:
- 'headers': an array of response headers, such as "x-powered-by" => "PHP/5.2.1"
- 'body': the response string sent by the server, as you would see it with you web browser
- 'response': an array of HTTP response codes. Typically, you'll want to have array('code'=>200, 'message'=>'OK')
- 'cookies': an array of cookie information
Now, let's see a few more complex examples and real world situations
Basic stuff: a simple GET request
Let's say your next plugin needs to poll Twitter's search service for latest tweets about rabbits. It's no more code than:
-
$url = 'http://search.twitter.com/search.json?q=rabbits';
-
$request = new WP_Http;
-
$result = $request->request( $url );
-
$json = $result['body'];
This is all you need for a JSON encoded string containing what you're looking for.
Slightly more advanced: a standard POST request
If you need to pass some parameters, say nick= 'ozh' and mood='happy', using the POST method, here is how you modify the request:
-
$body = array(
-
'nick' => 'ozh',
-
'mood' => 'happy'
-
);
-
$url = 'http://your.api.url/';
-
$request = new WP_Http;
-
$result = $request->request( $url, array( 'method' => 'POST', 'body' => $body) );
-
// test $result['response'] and if OK do something with $result['body']
Cool stuff: playing with an API which requires authentication
Let's say you want to update your Twitter stream. Their status update method is a simple request, but it needs authentication (ie http://twitter.com/statuses/update.xml asks for your Twitter login and password)
Authentication in HTTP requests is achieved by sending a base64 encoded string of the username, a colon and the password (ie "login:password")
Our Twitter example would be something simple like:
-
// You would edit the following:
-
$username = 'joe'; // Twitter login
-
$password = '123456'; // Twitter password
-
$message = "Hey neat, I'm posting with the API";
-
-
// Now, the HTTP request:
-
$api_url = 'http://twitter.com/statuses/update.xml';
-
$body = array( 'status' => $message );
-
$headers = array( 'Authorization' => 'Basic '.base64_encode("$username:$password") );
-
$request = new WP_Http;
-
$result = $request->request( $api_url , array( 'method' => 'POST', 'body' => $body, 'headers' => $headers ) );
Can't be more simple, right?
Learn more
Jacob Santos being the documentation advocate he is, his class is fully commented, so just read the source to learn more. For instance, there are shortcuts to do GET, POST or HEAD request, you can pass more parameters such as a timeout limit, you can play with cookies and much more.
Please ditch the deprecated stuff
I almost feel stupid for writing an how-to guide for something that easy to use, but the thing is I have the feeling this class is heavily underused. For instance, as of writing I'm reviewing the plugins that were submitted in the Plugin Competition 2009, and this class is not exactly popular. Well, it should.
Don't reinvent the wheel using cURL, it's not always installed. Don't use class Snoopy, it's completely deprecated. Just use WP_Http!
Related posts
Shorter URL
Want to share or tweet this post? Please use this short URL: http://ozh.in/of
Pages: [2] 1 » Show All
replied, on 14/Feb/10 at 1:37 am # :
Thanks for the handy tutorial :) I spent the past hour or so trying to figure out the best way to do this as I assumed the http API could only handle static files, but it appears I was wrong!
said, on 20/Sep/09 at 7:58 am # :
btw, one thing about this blog, it doesn't save my details, so I need to keep filling in Name, Mail etc everytime I come back.
pingback on 15/Sep/09 at 9:54 pm # :
[...] The last 5 post on planetOzh: Top 10 Most Common Coding Mistakes in WordPress PluginsBeing a Judge in the WordPress Plugin CompetitionSingle File WordPress Installer 2009 Open Source CMS Award: Nominate WordPress!How To Make HTTP Requests with WordPress [...]
pingback on 23/Aug/09 at 3:29 pm # :
[...] Shared How To Make HTTP Requests with WordPress « planetOzh [...]
pingback on 21/Aug/09 at 2:51 am # :
[...] you are going to use it in WordPress, then you can use the inbuilt WP_Http class instead of curl as suggested by Ozh. The following code shows you how it can be done in WordPress 1 2 3 4 5 6 7 8 9 10 11 function [...]
thought, on 20/Aug/09 at 9:09 am # :
WP_Http doesn't seem to work all the time. I've seen certain blogs showing
RSS Error: WP HTTP Error: 1: Operation not permitted
on the Dashboard. It really is cool though.
said, on 18/Aug/09 at 10:38 am # :
Makes sense...
btw, one thing about this blog, it doesn't save my details, so I need to keep filling in Name, Mail etc everytime I come back.
commented, on 18/Aug/09 at 10:29 am # :
Ajay » It's really the same thing, they are wrapper functions for the class.
replied, on 18/Aug/09 at 10:00 am # :
I haven't yet needed to use get and post requests till date but will keep this in mind.
I'm confused as to whether this is a better option of the wp_remote* functions?