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
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:
If there’s anything you’d add to the code above, don’t hesitate to do so in the comments.