How To Make HTTP Requests with WordPress


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

WordPress 3.x update: you now need to explicitly include the class if you intend to use it, that is start by adding the following lines:

PHP:

  1. if( !class_exists( ‘WP_Http’ ) )
  2.     include_once( ABSPATH . WPINC. ‘/class-http.php’ );

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:

PHP:

  1. $request = new WP_Http;
  2. $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:

PHP:

  1. $request = new WP_Http;
  2. $result = $request->request( $url );
  3. $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:

PHP:

  1. $body = array(
  2.    ‘nick’ => ‘ozh’,
  3.    ‘mood’ => ‘happy’
  4. );
  5. $request = new WP_Http;
  6. $result = $request->request( $url, array( ‘method’ => ‘POST’, ‘body’ => $body) );
  7. // 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:

PHP:

  1. // You would edit the following:
  2. $username = ‘joe’; // Twitter login
  3. $password = ‘123456’; // Twitter password
  4. $message = “Hey neat, I’m posting with the API”;
  5. // Now, the HTTP request:
  6. $body = array( ‘status’ => $message );
  7. $headers = array( ‘Authorization’ => ‘Basic ‘.base64_encode(“$username:$password”) );
  8. $request = new WP_Http;
  9. $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!

Source planetozh.com

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s