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.

From WordPress Codex

How to use wp_remote_fopen?

The function is really easy to use:

 $url = "";
 $content = wp_remote_fopen($url);

BUT, I really recommend you add some error-checking, perhaps something like:

	$url = "";
	$content = wp_remote_fopen($url);
	if ($content<-->'') {
		// Do whatever you want with the content here...
	} else {
		// Woops, I think something is going wrong!

I hope you enjoyed this little tip, and perhaps take a look at the other developer tips in the WordPress Development Tips category.

Read also  How To Check if the cURL PHP extension is loaded

4 thoughts on “Forget cURL, use wp_remote_fopen!”

  1. this would load an entire page from the URL from the to the and then you would parse whatever info out of the result?


      Spot on, my young padiwan 🙂

      There are also similar functions for RSS feeds, with methods to enable caching so you don’t request information too often from the poor RSS feeds.

  2. 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?! 🙂

    1. Lars Koudal

      Hi Emil

      Nice of you to drop by 🙂

      You are right of course. For more advanced usage wp_remote_fopen() is not powerful enough, and in those rare cases I turn to curl as well.

Leave a Comment

Your email address will not be published. Required fields are marked *