wp_safe_remote_get()
Sends a safe GET request and retrieves the raw HTTP response.
Use it for arbitrary URLs, including URLs supplied by a user or an external service. The original URL and every redirect are checked with wp_http_validate_url() to protect against SSRF attacks. Only HTTP and HTTPS protocols are supported.
Used By: download_url()
No Hooks.
Returns
Array|WP_Error.
array- HTTP response data.WP_Error- if the request fails or the URL is unsafe.
Usage
wp_safe_remote_get( $url, $args );
- $url(string) (required)
- Request URL. The original URL and every redirect must pass the security check.
- $args(array)
Request arguments. See WP_Http::request() for the complete list.
reject_unsafe_urlsis always forced totrue.Default:
[]
Examples
#1 Getting data from an external API
$response = wp_safe_remote_get(
'https://api.example.com/products/42',
[
'timeout' => 10,
'headers' => [
'Accept' => 'application/json',
],
]
);
if ( is_wp_error( $response ) ) {
return;
}
$status_code = wp_remote_retrieve_response_code( $response );
if ( 200 !== $status_code ) {
return;
}
$data = json_decode( wp_remote_retrieve_body( $response ), true );Notes
- See: wp_remote_request() For more information on the response array format.
- See: WP_Http::request() For default arguments information.
- See: wp_http_validate_url() For more information about how the URL is validated.
Changelog
| Since 3.6.0 | Introduced. |
wp_safe_remote_get() wp safe remote get code WP 7.0.4
function wp_safe_remote_get( $url, $args = array() ) {
$args['reject_unsafe_urls'] = true;
$http = _wp_http_get_object();
return $http->get( $url, $args );
}