cURL is a very popular PHP library that I’ve referenced in several posts other posts (1 and 2, for example). And it’s one that I think should be reviewed, explored, and possibly used by anyone working in PHP (yes, even those working in WordPress).

But because of the native WordPress APIs, we do have a level of abstraction that allows us to achieve much of the same functionality (if not the same functionality).

Specifically, I’m talking about wp_safe_remote_get.

This function is ideal when the HTTP request is being made to an arbitrary URL. The URL is validated to avoid redirection and request forgery attacks.

I specifically mention the safe variant of this function for the definition above (there is another variant, but it’s important to take precautions against arbitrary URLs for security reasons).

cURL and WordPress Requests

Anyway, so what might a function look like if we were to use this cURL library?

In short (and this is typical for most cURL requests):

  • initialize the cURL library,
  • set options specific to your request (which will vary based on said request),
  • make the request,
  • evaluate the response
  • catch any necessary exceptions.

And then if we were to use the same variation of the code in WordPress?

This is much smaller and arguably easier to read (at least for those working in WordPress). In terms of arguments, I’m also not passing anything into the function other than the URL.

If you read the linked API documentation, then you’ll see that we do have some control over that; however, it will vary depending on how you need to communicate with a given endpoint.

Further, how you handle the WP_Error is up to you. Returning an empty string is rarely the best option; however, for the purposes of this example, it’s sufficient. The case we’re primarily after is the body of the response and that’s the focus of the code.

When Do We Use One or the Other?

When it comes to working with cURL and WordPress remote requests and determining which method to use I tend to follow this rule:

  • If what I need can be achieved with a WordPress API function, I use it.
  • If not, I’ll use cURL.

I can’t provide a more solid rule.

Instead, look at the endpoint which you’re communicating, determine what level of control you need over the request, and make a decision on how you want to handle the response.

From there, you should have a good idea as to which library to use.