wp_safe_remote_get()WP 3.6.0

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_urls is always forced to true.

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

Changelog

Since 3.6.0 Introduced.

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 );
}