WP_Http::handle_redirects() WordPress Method

TheWP_Http::handle_redirects() function allows for redirect handling on the HTTP level. This function is called by the various HTTP request methods when a redirect is encountered. By default, this function will handle redirects for both 301 and 302 status codes, but can be customized to handle other status codes as well. This function can also be used to force the use of a specific HTTP request method for a given URL, regardless of the requested method.

WP_Http::handle_redirects( string $url, array $args, array $response ) #

Handles an HTTP redirect and follows it if appropriate.


Parameters

$url

(string)(Required)The URL which was requested.

$args

(array)(Required)The arguments which were used to make the request.

$response

(array)(Required)The response of the HTTP request.


Top ↑

Return

(array|false|WP_Error) An HTTP API response array if the redirect is successfully followed, false if no redirect is present, or a WP_Error object if there's an error.


Top ↑

Source

File: wp-includes/class-wp-http.php

	public static function handle_redirects( $url, $args, $response ) {
		// If no redirects are present, or, redirects were not requested, perform no action.
		if ( ! isset( $response['headers']['location'] ) || 0 === $args['_redirection'] ) {
			return false;
		}

		// Only perform redirections on redirection http codes.
		if ( $response['response']['code'] > 399 || $response['response']['code'] < 300 ) {
			return false;
		}

		// Don't redirect if we've run out of redirects.
		if ( $args['redirection']-- <= 0 ) {
			return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
		}

		$redirect_location = $response['headers']['location'];

		// If there were multiple Location headers, use the last header specified.
		if ( is_array( $redirect_location ) ) {
			$redirect_location = array_pop( $redirect_location );
		}

		$redirect_location = WP_Http::make_absolute_url( $redirect_location, $url );

		// POST requests should not POST to a redirected location.
		if ( 'POST' === $args['method'] ) {
			if ( in_array( $response['response']['code'], array( 302, 303 ), true ) ) {
				$args['method'] = 'GET';
			}
		}

		// Include valid cookies in the redirect process.
		if ( ! empty( $response['cookies'] ) ) {
			foreach ( $response['cookies'] as $cookie ) {
				if ( $cookie->test( $redirect_location ) ) {
					$args['cookies'][] = $cookie;
				}
			}
		}

		return wp_remote_request( $redirect_location, $args );
	}


Top ↑

Changelog

Changelog
VersionDescription
3.7.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.