Forget cURL, use wp_remote_fopen!

wp_remote_fopen – What it does and how to use it

It’s time for another WordPress Development Tip, today is a not so well known function, wp_remote_fopen.

When I search the internet for WordPress tips and tricks, I usually encounter small tutorials and tips that use either file_get_contents or cURL. The first, file_get_contents is a PHP function, which is usually turned off by most web hosting companies.

cURL is an extension built into PHP, and usually, works on most web hosts, but it requires a bit more tweaking and coding to use. If you need to send parameters along with your external call, such as login and password for Twitter, or something else, then you are best suited by using cURL for this. (See my other post on how to check if cURL is available: How To Check if the cURL PHP extension is loaded.)

However, if all you want is to download the content of a URL, you should use wp_remote_fopen, which is a built in function in WordPress with redundancy built in.

What do you mean redundancy?

The function first tries to load the external content via fopen (PHP) and then cURL if the first call fails. This means that using this WordPress function ensures it works on most web hosts. (Note: MOST!)

Returns the contents of a remote URI. Tries to retrieve the HTTP content with fopen first and then using cURL, if fopen can’t be used.

If you are going to use more php coding and classes like tidy or dom parse anyways, this it might not be that usefull. Some sites will block you id you dont include an identifyer like CURLOPT_USERAGENT – and how can you include options to wp_remote_fopen?! 🙂