In: , ,
On: 2009 / 08 / 16 Viewed: 40262 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

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. $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.

29 Blablas

    Pages: [3] 2 1 » Show All

  1. 29
    Ozh France »
    commented, on 31/May/10 at 7:11 pm # :

    Arvid » not sure I see where the problem is. When I wp_remote_get() a page that's gzipped, I get plain text just as a browser do. What's the particular API URL you're having problem with?

  2. 28
    Arvid Sweden »
    thought, on 31/May/10 at 5:28 pm # :

    i'm using this in a project i'm working on but there is one thing i just can't get to work. How do i use this to remote_get a GZip encoded api-response? i've tried with wp_remote_retrieve_body( wp_remote_get($url, array('decompress' => true)) ); and many other similair ways but i just can't get it to work. anybody got an idea how to do it?

  3. 27
    Konstantin Kovshenin Russia »
    wrote, on 16/May/10 at 5:43 pm # :

    Actually, it's not the WP_Http class you have to use now, but the wrapper functions - wp_remote_get, etc: http://codex.wordpress.org/HTTP_API

    Credit goes to @Viper007Bond ;)

    Cheers!

  4. 26
    EL Indonesia »
    said, on 29/Apr/10 at 11:24 am # :

    Nice article. I just started to write my first WP Plugin. Where can i find the complete list of "Wrapper Functions" for WordPress?

  5. 25
    Ozh France »
    thought, on 06/Apr/10 at 10:01 pm # :

    rev » yeah, totally, always used wrapper functions when they exist. I was just toying with the class to understand how it works

  6. 24
    rev United States »
    thought, on 06/Apr/10 at 7:53 pm # :

    lol, I just realize there are 3 pages of comments and saw your stuff from before talking about the wrapper functions. However my conundrum still stands I think, thoughts?

  7. 23
    rev United States »
    commented, on 06/Apr/10 at 7:52 pm # :

    I'm looking at the 3.0 changes (http://core.trac.wordpress.org/ticket/11559) on how they split out the class to class-http.php, and then considering your suggestion to essentially replicate what they did in http.php to include the class-http.php, and this feels a _little_ janky.

    This are my thoughts:

    while the WP_Http class SHOULD be present in all 2.7.x -> 2.9.x, say for some reason it wasn't, and we were in pre 3.x code, then the include would cause an exception because class-http.php isn't around until 3.x.

    so with that in mind, why not use the wrapper functions found in http.php instead of including a .php and instantiating a new WP_Http yourself. Look at it this way: unless you're looking for advanced functionality, where you would need the WP_Http object itself, why not just use the wrappers since you know they've been there since 2.7 and you know they'll be there in 3.0 without any extra includes?

    Thoughts? I'm working on 3.x compatibility right now for my plugin, and I don't want to commit and deploy something when I'm totally off the deep end ;)

  8. 22
    ximer Belgium »
    said, on 30/Mar/10 at 4:45 pm # :

    I still get the same error. I think I'm making some kind of other mistake(s), kinda new at this kind of things.

  9. 21
    Ozh France »
    thought, on 30/Mar/10 at 4:08 pm # :

    ximer » yeah, since I wrote this tutorial things changed slightly in WP. Now you need to explicitly include the class if you need it. I'll update the article.

Pages: [3] 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