Send an HTTP request to a URI.
Description
Please note: The only URI that are supported in the HTTP Transport implementation are the HTTP and HTTPS protocols.
Parameters
$url
stringrequired- The request URL.
$args
string|arrayoptional- Array or string of HTTP request arguments.
method
stringRequest method. Accepts'GET'
,'POST'
,'HEAD'
,'PUT'
,'DELETE'
,'TRACE'
,'OPTIONS'
, or'PATCH'
.
Some transports technically allow others, but should not be assumed. Default'GET'
.timeout
floatHow long the connection should stay open in seconds. Default 5.redirection
intNumber of allowed redirects. Not supported by all transports.
Default 5.httpversion
stringVersion of the HTTP protocol to use. Accepts'1.0'
and'1.1'
.
Default'1.0'
.user-agent
stringUser-agent value sent.
Default'WordPress/'
. get_bloginfo('version'
) . ‘; ‘ . get_bloginfo('url'
).reject_unsafe_urls
boolWhether to pass URLs through wp_http_validate_url() .
Default false.blocking
boolWhether the calling code requires the result of the request.
If set to false, the request will be sent to the remote server, and processing returned to the calling code immediately, the caller will know if the request succeeded or failed, but will not receive any response from the remote server. Default true.headers
string|arrayArray or string of headers to send with the request.
cookies
arrayList of cookies to send with the request.body
string|arrayBody to send with the request. Default null.compress
boolWhether to compress the $body when sending the request.
Default false.decompress
boolWhether to decompress a compressed response. If set to false and compressed content is returned in the response anyway, it will need to be separately decompressed. Default true.sslverify
boolWhether to verify SSL for the request. Default true.sslcertificates
stringAbsolute path to an SSL certificate .crt file.
Default ABSPATH . WPINC .'/certificates/ca-bundle.crt'
.stream
boolWhether to stream to a file. If set to true and no filename was given, it will be dropped it in the WP temp dir and its name will be set using the basename of the URL. Default false.filename
stringFilename of the file to write to when streaming. $stream must be set to true. Default null.limit_response_size
intSize in bytes to limit the response to. Default null.
Default:
array()
Return
array|WP_Error Array of response data, or a WP_Error instance upon error.headers
WpOrgRequestsUtilityCaseInsensitiveDictionaryResponse headers keyed by name.body
stringResponse body.response
arrayArray of HTTP response data.code
int|falseHTTP response status code.message
string|falseHTTP response message.
cookies
WP_HTTP_Cookie[]Array of cookies set by the server.filename
string|nullOptional. Filename of the response.http_response
WP_HTTP_Requests_Response|nullResponse object.
Source
public function request( $url, $args = array() ) { $defaults = array( 'method' => 'GET', /** * Filters the timeout value for an HTTP request. * * @since 2.7.0 * @since 5.1.0 The `$url` parameter was added. * * @param float $timeout_value Time in seconds until a request times out. Default 5. * @param string $url The request URL. */ 'timeout' => apply_filters( 'http_request_timeout', 5, $url ), /** * Filters the number of redirects allowed during an HTTP request. * * @since 2.7.0 * @since 5.1.0 The `$url` parameter was added. * * @param int $redirect_count Number of redirects allowed. Default 5. * @param string $url The request URL. */ 'redirection' => apply_filters( 'http_request_redirection_count', 5, $url ), /** * Filters the version of the HTTP protocol used in a request. * * @since 2.7.0 * @since 5.1.0 The `$url` parameter was added. * * @param string $version Version of HTTP used. Accepts '1.0' and '1.1'. Default '1.0'. * @param string $url The request URL. */ 'httpversion' => apply_filters( 'http_request_version', '1.0', $url ), /** * Filters the user agent value sent with an HTTP request. * * @since 2.7.0 * @since 5.1.0 The `$url` parameter was added. * * @param string $user_agent WordPress user agent string. * @param string $url The request URL. */ 'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . get_bloginfo( 'version' ) . '; ' . get_bloginfo( 'url' ), $url ), /** * Filters whether to pass URLs through wp_http_validate_url() in an HTTP request. * * @since 3.6.0 * @since 5.1.0 The `$url` parameter was added. * * @param bool $pass_url Whether to pass URLs through wp_http_validate_url(). Default false. * @param string $url The request URL. */ 'reject_unsafe_urls' => apply_filters( 'http_request_reject_unsafe_urls', false, $url ), 'blocking' => true, 'headers' => array(), 'cookies' => array(), 'body' => null, 'compress' => false, 'decompress' => true, 'sslverify' => true, 'sslcertificates' => ABSPATH . WPINC . '/certificates/ca-bundle.crt', 'stream' => false, 'filename' => null, 'limit_response_size' => null, ); // Pre-parse for the HEAD checks. $args = wp_parse_args( $args ); // By default, HEAD requests do not cause redirections. if ( isset( $args['method'] ) && 'HEAD' === $args['method'] ) { $defaults['redirection'] = 0; } $parsed_args = wp_parse_args( $args, $defaults ); /** * Filters the arguments used in an HTTP request. * * @since 2.7.0 * * @param array $parsed_args An array of HTTP request arguments. * @param string $url The request URL. */ $parsed_args = apply_filters( 'http_request_args', $parsed_args, $url ); // The transports decrement this, store a copy of the original value for loop purposes. if ( ! isset( $parsed_args['_redirection'] ) ) { $parsed_args['_redirection'] = $parsed_args['redirection']; } /** * Filters the preemptive return value of an HTTP request. * * Returning a non-false value from the filter will short-circuit the HTTP request and return * early with that value. A filter should return one of: * * - An array containing 'headers', 'body', 'response', 'cookies', and 'filename' elements * - A WP_Error instance * - boolean false to avoid short-circuiting the response * * Returning any other value may result in unexpected behavior. * * @since 2.9.0 * * @param false|array|WP_Error $response A preemptive return value of an HTTP request. Default false. * @param array $parsed_args HTTP request arguments. * @param string $url The request URL. */ $pre = apply_filters( 'pre_http_request', false, $parsed_args, $url ); if ( false !== $pre ) { return $pre; } if ( function_exists( 'wp_kses_bad_protocol' ) ) { if ( $parsed_args['reject_unsafe_urls'] ) { $url = wp_http_validate_url( $url ); } if ( $url ) { $url = wp_kses_bad_protocol( $url, array( 'http', 'https', 'ssl' ) ); } } $parsed_url = parse_url( $url ); if ( empty( $url ) || empty( $parsed_url['scheme'] ) ) { $response = new WP_Error( 'http_request_failed', __( 'A valid URL was not provided.' ) ); /** This action is documented in wp-includes/class-wp-http.php */ do_action( 'http_api_debug', $response, 'response', 'WpOrg\Requests\Requests', $parsed_args, $url ); return $response; } if ( $this->block_request( $url ) ) { $response = new WP_Error( 'http_request_not_executed', __( 'User has blocked requests through HTTP.' ) ); /** This action is documented in wp-includes/class-wp-http.php */ do_action( 'http_api_debug', $response, 'response', 'WpOrg\Requests\Requests', $parsed_args, $url ); return $response; } // If we are streaming to a file but no filename was given drop it in the WP temp dir // and pick its name using the basename of the $url. if ( $parsed_args['stream'] ) { if ( empty( $parsed_args['filename'] ) ) { $parsed_args['filename'] = get_temp_dir() . basename( $url ); } // Force some settings if we are streaming to a file and check for existence // and perms of destination directory. $parsed_args['blocking'] = true; if ( ! wp_is_writable( dirname( $parsed_args['filename'] ) ) ) { $response = new WP_Error( 'http_request_failed', __( 'Destination directory for file streaming does not exist or is not writable.' ) ); /** This action is documented in wp-includes/class-wp-http.php */ do_action( 'http_api_debug', $response, 'response', 'WpOrg\Requests\Requests', $parsed_args, $url ); return $response; } } if ( is_null( $parsed_args['headers'] ) ) { $parsed_args['headers'] = array(); } // WP allows passing in headers as a string, weirdly. if ( ! is_array( $parsed_args['headers'] ) ) { $processed_headers = WP_Http::processHeaders( $parsed_args['headers'] ); $parsed_args['headers'] = $processed_headers['headers']; } // Setup arguments. $headers = $parsed_args['headers']; $data = $parsed_args['body']; $type = $parsed_args['method']; $options = array( 'timeout' => $parsed_args['timeout'], 'useragent' => $parsed_args['user-agent'], 'blocking' => $parsed_args['blocking'], 'hooks' => new WP_HTTP_Requests_Hooks( $url, $parsed_args ), ); // Ensure redirects follow browser behavior. $options['hooks']->register( 'requests.before_redirect', array( static::class, 'browser_redirect_compatibility' ) ); // Validate redirected URLs. if ( function_exists( 'wp_kses_bad_protocol' ) && $parsed_args['reject_unsafe_urls'] ) { $options['hooks']->register( 'requests.before_redirect', array( static::class, 'validate_redirects' ) ); } if ( $parsed_args['stream'] ) { $options['filename'] = $parsed_args['filename']; } if ( empty( $parsed_args['redirection'] ) ) { $options['follow_redirects'] = false; } else { $options['redirects'] = $parsed_args['redirection']; } // Use byte limit, if we can. if ( isset( $parsed_args['limit_response_size'] ) ) { $options['max_bytes'] = $parsed_args['limit_response_size']; } // If we've got cookies, use and convert them to WpOrg\Requests\Cookie. if ( ! empty( $parsed_args['cookies'] ) ) { $options['cookies'] = WP_Http::normalize_cookies( $parsed_args['cookies'] ); } // SSL certificate handling. if ( ! $parsed_args['sslverify'] ) { $options['verify'] = false; $options['verifyname'] = false; } else { $options['verify'] = $parsed_args['sslcertificates']; } // All non-GET/HEAD requests should put the arguments in the form body. if ( 'HEAD' !== $type && 'GET' !== $type ) { $options['data_format'] = 'body'; } /** * Filters whether SSL should be verified for non-local requests. * * @since 2.8.0 * @since 5.1.0 The `$url` parameter was added. * * @param bool|string $ssl_verify Boolean to control whether to verify the SSL connection * or path to an SSL certificate. * @param string $url The request URL. */ $options['verify'] = apply_filters( 'https_ssl_verify', $options['verify'], $url ); // Check for proxies. $proxy = new WP_HTTP_Proxy(); if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) { $options['proxy'] = new WpOrg\Requests\Proxy\Http( $proxy->host() . ':' . $proxy->port() ); if ( $proxy->use_authentication() ) { $options['proxy']->use_authentication = true; $options['proxy']->user = $proxy->username(); $options['proxy']->pass = $proxy->password(); } } // Avoid issues where mbstring.func_overload is enabled. mbstring_binary_safe_encoding(); try { $requests_response = WpOrg\Requests\Requests::request( $url, $headers, $data, $type, $options ); // Convert the response into an array. $http_response = new WP_HTTP_Requests_Response( $requests_response, $parsed_args['filename'] ); $response = $http_response->to_array(); // Add the original object to the array. $response['http_response'] = $http_response; } catch ( WpOrg\Requests\Exception $e ) { $response = new WP_Error( 'http_request_failed', $e->getMessage() ); } reset_mbstring_encoding(); /** * Fires after an HTTP API response is received and before the response is returned. * * @since 2.8.0 * * @param array|WP_Error $response HTTP response or WP_Error object. * @param string $context Context under which the hook is fired. * @param string $class HTTP transport used. * @param array $parsed_args HTTP request arguments. * @param string $url The request URL. */ do_action( 'http_api_debug', $response, 'response', 'WpOrg\Requests\Requests', $parsed_args, $url ); if ( is_wp_error( $response ) ) { return $response; } if ( ! $parsed_args['blocking'] ) { return array( 'headers' => array(), 'body' => '', 'response' => array( 'code' => false, 'message' => false, ), 'cookies' => array(), 'http_response' => null, ); } /** * Filters a successful HTTP API response immediately before the response is returned. * * @since 2.9.0 * * @param array $response HTTP response. * @param array $parsed_args HTTP request arguments. * @param string $url The request URL. */ return apply_filters( 'http_response', $response, $parsed_args, $url ); }
Hooks
- apply_filters( ‘https_ssl_verify’,
bool|string $ssl_verify ,string $url ) Filters whether SSL should be verified for non-local requests.
- do_action( ‘http_api_debug’,
array|WP_Error $response ,string $context ,string $class ,array $parsed_args ,string $url ) Fires after an HTTP API response is received and before the response is returned.
- apply_filters( ‘http_headers_useragent’,
string $user_agent ,string $url ) Filters the user agent value sent with an HTTP request.
- apply_filters( ‘http_request_args’,
array $parsed_args ,string $url ) Filters the arguments used in an HTTP request.
- apply_filters( ‘http_request_redirection_count’,
int $redirect_count ,string $url ) Filters the number of redirects allowed during an HTTP request.
- apply_filters( ‘http_request_reject_unsafe_urls’,
bool $pass_url ,string $url ) Filters whether to pass URLs through wp_http_validate_url() in an HTTP request.
- apply_filters( ‘http_request_timeout’,
float $timeout_value ,string $url ) Filters the timeout value for an HTTP request.
- apply_filters( ‘http_request_version’,
string $version ,string $url ) Filters the version of the HTTP protocol used in a request.
- apply_filters( ‘http_response’,
array $response ,array $parsed_args ,string $url ) Filters a successful HTTP API response immediately before the response is returned.
- apply_filters( ‘pre_http_request’,
false|array|WP_Error $response ,array $parsed_args ,string $url ) Filters the preemptive return value of an HTTP request.
Related
Show 12 moreShow lessUses Description WP_HTTP_Requests_Hooks::__construct() wp-includes/class-wp-http-requests-hooks.php
Constructor.
reset_mbstring_encoding() wp-includes/functions.php
Resets the mbstring internal encoding to a users previously set encoding.
wp_http_validate_url() wp-includes/http.php
Validates a URL for safe use in the HTTP API.
wp_is_writable() wp-includes/functions.php
Determines if a directory is writable.
get_temp_dir() wp-includes/functions.php
Determines a writable directory for temporary files.
WP_HTTP_Requests_Response::__construct() wp-includes/class-wp-http-requests-response.php
Constructor.
mbstring_binary_safe_encoding() wp-includes/functions.php
Sets the mbstring internal encoding to a binary safe encoding when func_overload is enabled.
WP_Http::processHeaders() wp-includes/class-wp-http.php
Transforms header string into an array.
WP_Http::block_request() wp-includes/class-wp-http.php
Determines whether an HTTP API request to the given URL should be blocked.
wp_kses_bad_protocol() wp-includes/kses.php
Sanitizes a string and removed disallowed URL protocols.
WP_Http::normalize_cookies() wp-includes/class-wp-http.php
Normalizes cookies for using in Requests.
wp_parse_args() wp-includes/functions.php
Merges user defined arguments into defaults array.
get_bloginfo() wp-includes/general-template.php
Retrieves information about the current site.
apply_filters() wp-includes/plugin.php
Calls the callback functions that have been added to a filter hook.
do_action() wp-includes/plugin.php
Calls the callback functions that have been added to an action hook.
is_wp_error() wp-includes/load.php
Checks whether the given variable is a WordPress Error.
WP_Error::__construct() wp-includes/class-wp-error.php
Initializes the error.
Used by Description WP_Http::post() wp-includes/class-wp-http.php
Uses the POST HTTP method.
WP_Http::get() wp-includes/class-wp-http.php
Uses the GET HTTP method.
WP_Http::head() wp-includes/class-wp-http.php
Uses the HEAD HTTP method.
Changelog
Version Description 2.7.0 Introduced. User Contributed Notes
You must log in before being able to contribute a note or feedback.
$args['headers']
is a key => value associative array, unlike other PHP functions’ header settings that use entire header strings in an indexed array. E.g.:In documentation it is not clear what type should be passed to $args[‘body’] and when.
$args[‘body’] as indicated can be string|array but if you set the Content-Type to application/json and pass array to body it will not be encoded to json.
You need to do it manually