Using the PHP cURL extension

It sometimes happens that you need to get something from another server in PHP. It's tempting to just use file_get_contents('http://example.com/'), but if you do that you won't have any control over what happens if that server's down, or if it's redirecting. Using the PHP cURL extension, you get access to a powerful library for making HTTP requests and handling the output. Here's an example of how it works. There's far too many comments, and I may have done something wrong. If so, please don't kill me!

Use one of these instead

If you're making a web services request, use GuzzlePHP instead of this. It's fully-featured and extensible, allowing for things like batching, logging, an automated backoff for repeat requests to busy servers, and offers a tidy, minimal interface to any remote web service. Seriously, I can't stress enough just how awesome Guzzle is.

Kris Wallsmith's Buzz HTTP library offers a clean interface to cURL, with support for cookies, browser history, and redirection. Unlike the example below though, you'll have to do your own caching; it doesn't appear to offer that yet.

Fill in the blanks

If you use this code yourself, be a responsible coder and change the CURL_USERAGENT string! Make it yours. Read the known issues and notes after the example, too!

Notes and known issues


Disclaimer

It should go without saying, but any example code shown on this site is yours to use without obligation or warranty of any kind. As far as it's possible to do so, I release it into the public domain.