In: , ,
On: 2009 / 08 / 16 Viewed: 33230 times
Shorter URL for this post: http://ozh.in/of

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:

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. $url = 'http://search.twitter.com/search.json?q=rabbits';
  2. $request = new WP_Http;
  3. $result = $request->request( $url );
  4. $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. $url = 'http://your.api.url/';
  6. $request = new WP_Http;
  7. $result = $request->request( $url, array( 'method' => 'POST', 'body' => $body) );
  8. // 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.  
  6. // Now, the HTTP request:
  7. $api_url = 'http://twitter.com/statuses/update.xml';
  8. $body = array( 'status' => $message );
  9. $headers = array( 'Authorization' => 'Basic '.base64_encode("$username:$password") );
  10. $request = new WP_Http;
  11. $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

Metastuff

This entry "How To Make HTTP Requests with WordPress" was posted on 16/08/2009 at 8:30 pm and is tagged with , ,
Watch this discussion : Comments RSS 2.0.

19 Blablas

    Pages: [2] 1 » Show All

  1. 19
    Ryan Australia »
    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!

  2. 18
    pimapen Ukraine »
    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.

  3. 17
    Top 10 Most Common Coding Mistakes in Wo... United States »
    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 [...]

  4. 16
    Daily Digest for August 23rd | More Than... United States »
    pingback on 23/Aug/09 at 3:29 pm # :

    [...] Shared How To Make HTTP Requests with WordPress « planetOzh [...]

  5. 15
    Associating urls created with bit.ly API... United States »
    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 [...]

  6. 14
    Mike Lopez Canada »
    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.

  7. 13
    Ajay Australia »
    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.

  8. 12
    Ozh France »
    commented, on 18/Aug/09 at 10:29 am # :

    Ajay » It's really the same thing, they are wrapper functions for the class.

  9. 11
    Ajay Australia »
    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?

Pages: [2] 1 » Show All

Leave a Reply

Comment Guidelines or Die

  • HTML: You can use these tags: <a href=""> <em> <i> <b> <strong> <blockquote>
  • Posting code: Post raw code (no <> &lt; etc) within appropriate tags : [php][/php], [css][/css], [html][/html], [js][/js], [sql][/sql], [xml][/xml], or generic [code][code]
  • Gravatars: Curious about the little images next to each commenter's name ? Go to Gravatar.
  • Spam: Various spam plugins on patrol. I'll put pins in a Voodoo doll if you spam me.
  • I will mark as Spam test comments, all comments with SEO names (ie "My Cool Online Shop" instead of "Joe") or containing forum-like signatures.

Read more ?

Close
E-mail It