wp_safe_remote_request()WP 3.6.0

Retrieve the raw response from a safe HTTP request.

This function is ideal when the HTTP request is being made to an arbitrary URL. The URL, and every URL it redirects to, are validated with wp_http_validate_url() to avoid Server Side Request Forgery attacks (SSRF).

No Hooks.

Return

Array|WP_Error. The response or WP_Error on failure. See WP_Http::request() for information on return value.

Usage

wp_safe_remote_request( $url, $args );
$url(string) (required)
URL to retrieve.
$args(array)
Request arguments. See WP_Http::request() for information on accepted arguments.
Default: empty array

Examples

0

#1 Get server response data by URL

Suppose we want to get a page http://wordpress.org, but first we have to check if the server returned the status code 200 (OK):

$res = wp_safe_remote_request('http://wordpress.org');

print_r( $res );

We Get:

Array (
	[headers] => Array
		(
			[server] => nginx
			[date] => Sun, 02 Nov 2014 21:01:46 GMT
			[content-type] => text/html; charset=utf-8
			[connection] => close
			[vary] => Accept-Encoding
			[x-frame-options] => SAMEORIGIN
			[x-nc] => HIT lax 250
		)

	[body] => <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en">
...
	[response] => Array
		(
			[code] => 200
			[message] => OK
		)

	[cookies] => Array
		(
		)

	[filename] =>

Notes

Changelog

Since 3.6.0 Introduced.

wp_safe_remote_request() code WP 6.7.1

function wp_safe_remote_request( $url, $args = array() ) {
	$args['reject_unsafe_urls'] = true;
	$http                       = _wp_http_get_object();
	return $http->request( $url, $args );
}