Yesterday, I shared a post on how to use
wp_remote_get but I left out an alternative function:
wp_safe_remote_get. The original goal was to use the first post to show:
- What the original function accepts,
- How to use the original function,
- What the original function returns,
- What an implementation make look like.
And then I was going to take a look at
wp_safe_remote_get. But there’s a challenge: I have smart friends. Shortly after I published the post, I get a response from Roy:
— Roy Sivan (@royboy789) January 10, 2017
Thanks, Roy! (Be sure to say “Hi!” to him. :)
But seriously, the follow-up to yesterday’s post is exactly that:
wp_safe_remote_get. And it’s how to determine the difference in the two functions and when you’d use one over the other.
Straight from the API docs, we learn:
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.
And similar to its counterpart, it accepts a URL and a series of arguments that can specify how the request is made.
Furthermore, just as
wp_remote_get, it also returns an array of the response data or an instance of
WP_Error if the request fails.
Using this function isn’t different than using the previous, but it raises the question:
When do we use one over the other? More specifically, when do we use
Read The Source
When you’re faced with a situation like this, the first best thing to do is to read the source:
If you read the links above you’ll notice that the latter rejects the “unsafe URLs” which is determined by wp_http_validate_url through a series of advanced checks.
But Still, Which Do I Use?
This still leaves the question unanswered, doesn’t it? I think it’s easy to make the blanket statement that you should always be using wp_safe_remote_get (or wp_safe_remote_post, for that matter).
All projects are different, though.
For example, if you’re working on a plugin that’s only going to be used on an intranet and you have control over, say, a whitelist of URL that can be passed into the function, then you’re fine using the former.
If, however, you’re exposing the latter to users, always use the safe version of the function.
My rule of thumb is this (and it’s similar to sanitization):
If users are going to interact with the function, then make sure they are interacting with the safest version of the code possible.
Otherwise, too much is at risk.