Quick Tip: An Alternative To file_get_contents

One of the more common PHP functions developers use in order to make remote requests is file_get_contents. The function makes it easy to send requests to another URL and then handle the response.

It’s especially handy if you need to make an Ajax request to another site but aren’t allowed to do so from the client-side because of cross-site-scripting.

That said, cURL is often a better option than file_get_contents because it gives you far more control over the options that are set when setting up the request to be made. file_get_contents simply doesn’t do that. Instead, it provides enough options for making simple GET requests.

No, not that kind of curl.

For these reasons, it’s often a good idea to use cURL when you need to provide a more fine-tuned request. Even more so, it’s helpful to have all of the functionality wrapped up in a utility function you can drop in your project whenever you need it.

Alternative To file_get_contents

Given all of the above, here’s a very basic function you can be use in place of file_get_contents that uses cURL to complete the request as in this gist;

Notice in the code above, there aren’t many options that are being specified for cURL. It’s harder to anticipate exactly what you may need given your project, so the function is left as simple as possible so you can add (or even remove) the options that you don’t need to further refine your request.

For more information about either of the functions listed above, I recommend checking out the PHP manual for:

But then I wouldn’t have had the pleasure of commenting! Or maybe I’d say what I should say – thanks for keeping all the options fresh in our minds, even when we’ve forgotten what you showed us before.

The reason I stopped using file_get_contents for remote files is I found out the hard way that some installs of PHP block file_get_contents for remote URLs. The same holds true forfopen and it’s related functions.

I can never remember what the cURL options are or when to use each. In WordPress, I leverage the HTTP API. Outside of WP, I like using Guzzle to handle the low level cURL.

Just Getting Started with WordPress?

I write a lot about WordPress development but if you're just getting started, I recommend checking out WPBeginner. They have free training videos, glossary, and more.

WPSessions hosts some of the best WordPress training you’ll find anywhere from many well-known speakers.

If there’s something you’d like to learn, and it’s not already covered here, it’s probably been covered at WPSessions. If you use the special link below you can watch your first session for free and get a steep discount on the full-access VIP membership.