[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> http.php (source)

   1  <?php
   2  /**
   3   * Core HTTP Request API
   4   *
   5   * Standardizes the HTTP requests for WordPress. Handles cookies, gzip encoding and decoding, chunk
   6   * decoding, if HTTP 1.1 and various other difficult HTTP protocol implementations.
   7   *
   8   * @package WordPress
   9   * @subpackage HTTP
  10   */
  11  
  12  /**
  13   * Returns the initialized WP_Http Object
  14   *
  15   * @since 2.7.0
  16   * @access private
  17   *
  18   * @return WP_Http HTTP Transport object.
  19   */
  20  function _wp_http_get_object() {
  21      static $http = null;
  22  
  23      if ( is_null( $http ) ) {
  24          $http = new WP_Http();
  25      }
  26      return $http;
  27  }
  28  
  29  /**
  30   * Retrieves the raw response from a safe HTTP request.
  31   *
  32   * This function is ideal when the HTTP request is being made to an arbitrary
  33   * URL. The URL, and every URL it redirects to, are validated with wp_http_validate_url()
  34   * to avoid Server Side Request Forgery attacks (SSRF).
  35   *
  36   * The only supported protocols are `http` and `https`.
  37   *
  38   * @since 3.6.0
  39   *
  40   * @see wp_remote_request() For more information on the response array format.
  41   * @see WP_Http::request() For default arguments information.
  42   * @see wp_http_validate_url() For more information about how the URL is validated.
  43   *
  44   * @link https://owasp.org/www-community/attacks/Server_Side_Request_Forgery
  45   *
  46   * @param string $url  URL to retrieve.
  47   * @param array  $args Optional. Request arguments. Default empty array.
  48   *                     See WP_Http::request() for information on accepted arguments.
  49   * @return array|WP_Error The response or WP_Error on failure.
  50   *                        See WP_Http::request() for information on return value.
  51   *
  52   * @phpstan-return array{
  53   *     headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array<string, string>,
  54   *     body: string,
  55   *     response: array{code: int|false, message: string|false},
  56   *     cookies: WP_Http_Cookie[],
  57   *     filename?: string|null,
  58   *     http_response?: WP_HTTP_Requests_Response|null,
  59   * }|WP_Error
  60   */
  61  function wp_safe_remote_request( $url, $args = array() ) {
  62      $args['reject_unsafe_urls'] = true;
  63      $http                       = _wp_http_get_object();
  64      return $http->request( $url, $args );
  65  }
  66  
  67  /**
  68   * Retrieves the raw response from a safe HTTP request using the GET method.
  69   *
  70   * This function is ideal when the HTTP request is being made to an arbitrary
  71   * URL. The URL, and every URL it redirects to, are validated with wp_http_validate_url()
  72   * to avoid Server Side Request Forgery attacks (SSRF).
  73   *
  74   * The only supported protocols are `http` and `https`.
  75   *
  76   * @since 3.6.0
  77   *
  78   * @see wp_remote_request() For more information on the response array format.
  79   * @see WP_Http::request() For default arguments information.
  80   * @see wp_http_validate_url() For more information about how the URL is validated.
  81   *
  82   * @link https://owasp.org/www-community/attacks/Server_Side_Request_Forgery
  83   *
  84   * @param string $url  URL to retrieve.
  85   * @param array  $args Optional. Request arguments. Default empty array.
  86   *                     See WP_Http::request() for information on accepted arguments.
  87   * @return array|WP_Error The response or WP_Error on failure.
  88   *                        See WP_Http::request() for information on return value.
  89   *
  90   * @phpstan-return array{
  91   *     headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array<string, string>,
  92   *     body: string,
  93   *     response: array{code: int|false, message: string|false},
  94   *     cookies: WP_Http_Cookie[],
  95   *     filename?: string|null,
  96   *     http_response?: WP_HTTP_Requests_Response|null,
  97   * }|WP_Error
  98   */
  99  function wp_safe_remote_get( $url, $args = array() ) {
 100      $args['reject_unsafe_urls'] = true;
 101      $http                       = _wp_http_get_object();
 102      return $http->get( $url, $args );
 103  }
 104  
 105  /**
 106   * Retrieves the raw response from a safe HTTP request using the POST method.
 107   *
 108   * This function is ideal when the HTTP request is being made to an arbitrary
 109   * URL. The URL, and every URL it redirects to, are validated with wp_http_validate_url()
 110   * to avoid Server Side Request Forgery attacks (SSRF).
 111   *
 112   * The only supported protocols are `http` and `https`.
 113   *
 114   * @since 3.6.0
 115   *
 116   * @see wp_remote_request() For more information on the response array format.
 117   * @see WP_Http::request() For default arguments information.
 118   * @see wp_http_validate_url() For more information about how the URL is validated.
 119   *
 120   * @link https://owasp.org/www-community/attacks/Server_Side_Request_Forgery
 121   *
 122   * @param string $url  URL to retrieve.
 123   * @param array  $args Optional. Request arguments. Default empty array.
 124   *                     See WP_Http::request() for information on accepted arguments.
 125   * @return array|WP_Error The response or WP_Error on failure.
 126   *                        See WP_Http::request() for information on return value.
 127   *
 128   * @phpstan-return array{
 129   *     headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array<string, string>,
 130   *     body: string,
 131   *     response: array{code: int|false, message: string|false},
 132   *     cookies: WP_Http_Cookie[],
 133   *     filename?: string|null,
 134   *     http_response?: WP_HTTP_Requests_Response|null,
 135   * }|WP_Error
 136   */
 137  function wp_safe_remote_post( $url, $args = array() ) {
 138      $args['reject_unsafe_urls'] = true;
 139      $http                       = _wp_http_get_object();
 140      return $http->post( $url, $args );
 141  }
 142  
 143  /**
 144   * Retrieves the raw response from a safe HTTP request using the HEAD method.
 145   *
 146   * This function is ideal when the HTTP request is being made to an arbitrary
 147   * URL. The URL, and every URL it redirects to, are validated with wp_http_validate_url()
 148   * to avoid Server Side Request Forgery attacks (SSRF).
 149   *
 150   * The only supported protocols are `http` and `https`.
 151   *
 152   * @since 3.6.0
 153   *
 154   * @see wp_remote_request() For more information on the response array format.
 155   * @see WP_Http::request() For default arguments information.
 156   * @see wp_http_validate_url() For more information about how the URL is validated.
 157   *
 158   * @link https://owasp.org/www-community/attacks/Server_Side_Request_Forgery
 159   *
 160   * @param string $url  URL to retrieve.
 161   * @param array  $args Optional. Request arguments. Default empty array.
 162   *                     See WP_Http::request() for information on accepted arguments.
 163   * @return array|WP_Error The response or WP_Error on failure.
 164   *                        See WP_Http::request() for information on return value.
 165   *
 166   * @phpstan-return array{
 167   *     headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array<string, string>,
 168   *     body: string,
 169   *     response: array{code: int|false, message: string|false},
 170   *     cookies: WP_Http_Cookie[],
 171   *     filename?: string|null,
 172   *     http_response?: WP_HTTP_Requests_Response|null,
 173   * }|WP_Error
 174   */
 175  function wp_safe_remote_head( $url, $args = array() ) {
 176      $args['reject_unsafe_urls'] = true;
 177      $http                       = _wp_http_get_object();
 178      return $http->head( $url, $args );
 179  }
 180  
 181  /**
 182   * Performs an HTTP request and returns its response.
 183   *
 184   * There are other API functions available which abstract away the HTTP method:
 185   *
 186   *  - Default 'GET'  for wp_remote_get()
 187   *  - Default 'POST' for wp_remote_post()
 188   *  - Default 'HEAD' for wp_remote_head()
 189   *
 190   * Important: If the URL is user-controlled, use `wp_safe_remote_request()` instead.
 191   *
 192   * @since 2.7.0
 193   *
 194   * @see WP_Http::request() For information on default arguments.
 195   *
 196   * @param string $url  URL to retrieve.
 197   * @param array  $args Optional. Request arguments. Default empty array.
 198   *                     See WP_Http::request() for information on accepted arguments.
 199   * @return array|WP_Error The response array or a WP_Error on failure.
 200   *                        See WP_Http::request() for information on return value.
 201   *
 202   * @phpstan-return array{
 203   *     headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array<string, string>,
 204   *     body: string,
 205   *     response: array{code: int|false, message: string|false},
 206   *     cookies: WP_Http_Cookie[],
 207   *     filename?: string|null,
 208   *     http_response?: WP_HTTP_Requests_Response|null,
 209   * }|WP_Error
 210   */
 211  function wp_remote_request( $url, $args = array() ) {
 212      $http = _wp_http_get_object();
 213      return $http->request( $url, $args );
 214  }
 215  
 216  /**
 217   * Performs an HTTP request using the GET method and returns its response.
 218   *
 219   * Important: If the URL is user-controlled, use `wp_safe_remote_get()` instead.
 220   *
 221   * @since 2.7.0
 222   *
 223   * @see wp_remote_request() For more information on the response array format.
 224   * @see WP_Http::request() For default arguments information.
 225   *
 226   * @param string $url  URL to retrieve.
 227   * @param array  $args Optional. Request arguments. Default empty array.
 228   *                     See WP_Http::request() for information on accepted arguments.
 229   * @return array|WP_Error The response or WP_Error on failure.
 230   *                        See WP_Http::request() for information on return value.
 231   *
 232   * @phpstan-return array{
 233   *     headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array<string, string>,
 234   *     body: string,
 235   *     response: array{code: int|false, message: string|false},
 236   *     cookies: WP_Http_Cookie[],
 237   *     filename?: string|null,
 238   *     http_response?: WP_HTTP_Requests_Response|null,
 239   * }|WP_Error
 240   */
 241  function wp_remote_get( $url, $args = array() ) {
 242      $http = _wp_http_get_object();
 243      return $http->get( $url, $args );
 244  }
 245  
 246  /**
 247   * Performs an HTTP request using the POST method and returns its response.
 248   *
 249   * Important: If the URL is user-controlled, use `wp_safe_remote_post()` instead.
 250   *
 251   * @since 2.7.0
 252   *
 253   * @see wp_remote_request() For more information on the response array format.
 254   * @see WP_Http::request() For default arguments information.
 255   *
 256   * @param string $url  URL to retrieve.
 257   * @param array  $args Optional. Request arguments. Default empty array.
 258   *                     See WP_Http::request() for information on accepted arguments.
 259   * @return array|WP_Error The response or WP_Error on failure.
 260   *                        See WP_Http::request() for information on return value.
 261   *
 262   * @phpstan-return array{
 263   *     headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array<string, string>,
 264   *     body: string,
 265   *     response: array{code: int|false, message: string|false},
 266   *     cookies: WP_Http_Cookie[],
 267   *     filename?: string|null,
 268   *     http_response?: WP_HTTP_Requests_Response|null,
 269   * }|WP_Error
 270   */
 271  function wp_remote_post( $url, $args = array() ) {
 272      $http = _wp_http_get_object();
 273      return $http->post( $url, $args );
 274  }
 275  
 276  /**
 277   * Performs an HTTP request using the HEAD method and returns its response.
 278   *
 279   * Important: If the URL is user-controlled, use `wp_safe_remote_head()` instead.
 280   *
 281   * @since 2.7.0
 282   *
 283   * @see wp_remote_request() For more information on the response array format.
 284   * @see WP_Http::request() For default arguments information.
 285   *
 286   * @param string $url  URL to retrieve.
 287   * @param array  $args Optional. Request arguments. Default empty array.
 288   *                     See WP_Http::request() for information on accepted arguments.
 289   * @return array|WP_Error The response or WP_Error on failure.
 290   *                        See WP_Http::request() for information on return value.
 291   *
 292   * @phpstan-return array{
 293   *     headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array<string, string>,
 294   *     body: string,
 295   *     response: array{code: int|false, message: string|false},
 296   *     cookies: WP_Http_Cookie[],
 297   *     filename?: string|null,
 298   *     http_response?: WP_HTTP_Requests_Response|null,
 299   * }|WP_Error
 300   */
 301  function wp_remote_head( $url, $args = array() ) {
 302      $http = _wp_http_get_object();
 303      return $http->head( $url, $args );
 304  }
 305  
 306  /**
 307   * Retrieves only the headers from the raw response.
 308   *
 309   * @since 2.7.0
 310   * @since 4.6.0 Return value changed from an array to an WpOrg\Requests\Utility\CaseInsensitiveDictionary instance.
 311   *
 312   * @see \WpOrg\Requests\Utility\CaseInsensitiveDictionary
 313   *
 314   * @param array|WP_Error $response HTTP response.
 315   * @return \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array The headers of the response, or empty array
 316   *                                                                 if incorrect parameter given.
 317   */
 318  function wp_remote_retrieve_headers( $response ) {
 319      if ( is_wp_error( $response ) || ! isset( $response['headers'] ) ) {
 320          return array();
 321      }
 322  
 323      return $response['headers'];
 324  }
 325  
 326  /**
 327   * Retrieves a single header by name from the raw response.
 328   *
 329   * @since 2.7.0
 330   *
 331   * @param array|WP_Error $response HTTP response.
 332   * @param string         $header   Header name to retrieve value from.
 333   * @return array|string The header(s) value(s). Array if multiple headers with the same name are retrieved.
 334   *                      Empty string if incorrect parameter given, or if the header doesn't exist.
 335   */
 336  function wp_remote_retrieve_header( $response, $header ) {
 337      if ( is_wp_error( $response ) || ! isset( $response['headers'] ) ) {
 338          return '';
 339      }
 340  
 341      return $response['headers'][ $header ] ?? '';
 342  }
 343  
 344  /**
 345   * Retrieves only the response code from the raw response.
 346   *
 347   * Will return an empty string if incorrect parameter value is given.
 348   *
 349   * @since 2.7.0
 350   *
 351   * @param array|WP_Error $response HTTP response.
 352   * @return int|string The response code as an integer. Empty string if incorrect parameter given.
 353   */
 354  function wp_remote_retrieve_response_code( $response ) {
 355      if ( is_wp_error( $response ) || ! isset( $response['response'] ) || ! is_array( $response['response'] ) ) {
 356          return '';
 357      }
 358  
 359      return $response['response']['code'];
 360  }
 361  
 362  /**
 363   * Retrieves only the response message from the raw response.
 364   *
 365   * Will return an empty string if incorrect parameter value is given.
 366   *
 367   * @since 2.7.0
 368   *
 369   * @param array|WP_Error $response HTTP response.
 370   * @return string The response message. Empty string if incorrect parameter given.
 371   */
 372  function wp_remote_retrieve_response_message( $response ) {
 373      if ( is_wp_error( $response ) || ! isset( $response['response'] ) || ! is_array( $response['response'] ) ) {
 374          return '';
 375      }
 376  
 377      return $response['response']['message'];
 378  }
 379  
 380  /**
 381   * Retrieves only the body from the raw response.
 382   *
 383   * @since 2.7.0
 384   *
 385   * @param array|WP_Error $response HTTP response.
 386   * @return string The body of the response. Empty string if no body or incorrect parameter given.
 387   */
 388  function wp_remote_retrieve_body( $response ) {
 389      if ( is_wp_error( $response ) || ! isset( $response['body'] ) ) {
 390          return '';
 391      }
 392  
 393      return $response['body'];
 394  }
 395  
 396  /**
 397   * Retrieves only the cookies from the raw response.
 398   *
 399   * @since 4.4.0
 400   *
 401   * @param array|WP_Error $response HTTP response.
 402   * @return WP_Http_Cookie[] An array of `WP_Http_Cookie` objects from the response.
 403   *                          Empty array if there are none, or the response is a WP_Error.
 404   */
 405  function wp_remote_retrieve_cookies( $response ) {
 406      if ( is_wp_error( $response ) || empty( $response['cookies'] ) ) {
 407          return array();
 408      }
 409  
 410      return $response['cookies'];
 411  }
 412  
 413  /**
 414   * Retrieves a single cookie by name from the raw response.
 415   *
 416   * @since 4.4.0
 417   *
 418   * @param array|WP_Error $response HTTP response.
 419   * @param string         $name     The name of the cookie to retrieve.
 420   * @return WP_Http_Cookie|string The `WP_Http_Cookie` object, or empty string
 421   *                               if the cookie is not present in the response.
 422   */
 423  function wp_remote_retrieve_cookie( $response, $name ) {
 424      $cookies = wp_remote_retrieve_cookies( $response );
 425  
 426      if ( empty( $cookies ) ) {
 427          return '';
 428      }
 429  
 430      foreach ( $cookies as $cookie ) {
 431          if ( $cookie->name === $name ) {
 432              return $cookie;
 433          }
 434      }
 435  
 436      return '';
 437  }
 438  
 439  /**
 440   * Retrieves a single cookie's value by name from the raw response.
 441   *
 442   * @since 4.4.0
 443   *
 444   * @param array|WP_Error $response HTTP response.
 445   * @param string         $name     The name of the cookie to retrieve.
 446   * @return string The value of the cookie, or empty string
 447   *                if the cookie is not present in the response.
 448   */
 449  function wp_remote_retrieve_cookie_value( $response, $name ) {
 450      $cookie = wp_remote_retrieve_cookie( $response, $name );
 451  
 452      if ( ! ( $cookie instanceof WP_Http_Cookie ) ) {
 453          return '';
 454      }
 455  
 456      return $cookie->value ?? '';
 457  }
 458  
 459  /**
 460   * Determines if there is an HTTP Transport that can process this request.
 461   *
 462   * @since 3.2.0
 463   *
 464   * @param array  $capabilities Array of capabilities to test or a wp_remote_request() $args array.
 465   * @param string $url          Optional. If given, will check if the URL requires SSL and adds
 466   *                             that requirement to the capabilities array.
 467   *
 468   * @return bool
 469   */
 470  function wp_http_supports( $capabilities = array(), $url = null ) {
 471      $capabilities = wp_parse_args( $capabilities );
 472  
 473      $count = count( $capabilities );
 474  
 475      // If we have a numeric $capabilities array, spoof a wp_remote_request() associative $args array.
 476      if ( $count && count( array_filter( array_keys( $capabilities ), 'is_numeric' ) ) === $count ) {
 477          $capabilities = array_combine( array_values( $capabilities ), array_fill( 0, $count, true ) );
 478      }
 479  
 480      if ( $url && ! isset( $capabilities['ssl'] ) ) {
 481          $scheme = parse_url( $url, PHP_URL_SCHEME );
 482          if ( 'https' === $scheme || 'ssl' === $scheme ) {
 483              $capabilities['ssl'] = true;
 484          }
 485      }
 486  
 487      return WpOrg\Requests\Requests::has_capabilities( $capabilities );
 488  }
 489  
 490  /**
 491   * Gets the HTTP Origin of the current request.
 492   *
 493   * @since 3.4.0
 494   *
 495   * @return string URL of the origin. Empty string if no origin.
 496   */
 497  function get_http_origin() {
 498      $origin = '';
 499      if ( ! empty( $_SERVER['HTTP_ORIGIN'] ) ) {
 500          $origin = $_SERVER['HTTP_ORIGIN'];
 501      }
 502  
 503      /**
 504       * Changes the origin of an HTTP request.
 505       *
 506       * @since 3.4.0
 507       *
 508       * @param string $origin The HTTP origin for the request.
 509       */
 510      return apply_filters( 'http_origin', $origin );
 511  }
 512  
 513  /**
 514   * Retrieves list of allowed HTTP origins.
 515   *
 516   * @since 3.4.0
 517   *
 518   * @return string[] Array of origin URLs.
 519   */
 520  function get_allowed_http_origins() {
 521      $admin_origin = parse_url( admin_url() );
 522      $home_origin  = parse_url( home_url() );
 523  
 524      // @todo Preserve port?
 525      $allowed_origins = array_unique(
 526          array(
 527              'http://' . $admin_origin['host'],
 528              'https://' . $admin_origin['host'],
 529              'http://' . $home_origin['host'],
 530              'https://' . $home_origin['host'],
 531          )
 532      );
 533  
 534      /**
 535       * Changes the origin types allowed for HTTP requests.
 536       *
 537       * @since 3.4.0
 538       *
 539       * @param string[] $allowed_origins Array of allowed HTTP origins.
 540       */
 541      return apply_filters( 'allowed_http_origins', $allowed_origins );
 542  }
 543  
 544  /**
 545   * Determines if the HTTP origin is an authorized one.
 546   *
 547   * @since 3.4.0
 548   *
 549   * @param string|null $origin Origin URL. If not provided, the value of get_http_origin() is used.
 550   * @return string Origin URL if allowed, empty string if not.
 551   */
 552  function is_allowed_http_origin( $origin = null ) {
 553      $origin_arg = $origin;
 554  
 555      if ( null === $origin ) {
 556          $origin = get_http_origin();
 557      }
 558  
 559      if ( $origin && ! in_array( $origin, get_allowed_http_origins(), true ) ) {
 560          $origin = '';
 561      }
 562  
 563      /**
 564       * Changes the allowed HTTP origin result.
 565       *
 566       * @since 3.4.0
 567       *
 568       * @param string $origin     Origin URL if allowed, empty string if not.
 569       * @param string $origin_arg Original origin string passed into is_allowed_http_origin function.
 570       */
 571      return apply_filters( 'allowed_http_origin', $origin, $origin_arg );
 572  }
 573  
 574  /**
 575   * Sends Access-Control-Allow-Origin and related headers if the current request
 576   * is from an allowed origin.
 577   *
 578   * If the request is an OPTIONS request, the script exits with either access
 579   * control headers sent, or a 403 response if the origin is not allowed. For
 580   * other request methods, you will receive a return value.
 581   *
 582   * @since 3.4.0
 583   *
 584   * @return string|false Returns the origin URL if headers are sent. Returns false
 585   *                      if headers are not sent.
 586   */
 587  function send_origin_headers() {
 588      $origin = get_http_origin();
 589  
 590      if ( is_allowed_http_origin( $origin ) ) {
 591          header( 'Access-Control-Allow-Origin: ' . $origin );
 592          header( 'Access-Control-Allow-Credentials: true' );
 593          if ( 'OPTIONS' === $_SERVER['REQUEST_METHOD'] ) {
 594              exit;
 595          }
 596          return $origin;
 597      }
 598  
 599      if ( 'OPTIONS' === $_SERVER['REQUEST_METHOD'] ) {
 600          status_header( 403 );
 601          exit;
 602      }
 603  
 604      return false;
 605  }
 606  
 607  /**
 608   * Validates a URL as safe for use in the HTTP API.
 609   *
 610   * The only supported protocols are `http` and `https`.
 611   *
 612   * Examples of URLs that are considered unsafe:
 613   *
 614   * - `ftp://example.com/caniload.php` - Invalid protocol - only http and https are allowed.
 615   * - `http:///example.com/caniload.php` - Malformed URL.
 616   * - `http://user:pass@example.com/caniload.php` - Login information.
 617   * - `http://example.invalid/caniload.php` - Invalid hostname, as the IP cannot be looked up in DNS.
 618   *
 619   * Examples of URLs that are considered unsafe by default but can be allowed with filters:
 620   *
 621   * - `http://192.168.0.1/caniload.php` - IP address from LAN network.
 622   *   This can be changed with the {@see 'http_request_host_is_external'} filter.
 623   * - `http://198.143.164.252:81/caniload.php` - By default, only ports 80, 443, and 8080 are allowed.
 624   *   This can be changed with the {@see 'http_allowed_safe_ports'} filter.
 625   *
 626   * @since 3.5.2
 627   *
 628   * @param string $url Request URL.
 629   * @return string|false Returns false if the URL is not safe, or the original URL if it is safe.
 630   *
 631   * @phpstan-return ( $url is numeric|'' ? false : string|false )
 632   */
 633  function wp_http_validate_url( $url ) {
 634      if ( ! is_string( $url ) || '' === $url || is_numeric( $url ) ) {
 635          return false;
 636      }
 637  
 638      $original_url = $url;
 639      $url          = wp_kses_bad_protocol( $url, array( 'http', 'https' ) );
 640      if ( ! $url || strtolower( $url ) !== strtolower( $original_url ) ) {
 641          return false;
 642      }
 643  
 644      $parsed_url = parse_url( $url );
 645      if ( ! $parsed_url || empty( $parsed_url['host'] ) ) {
 646          return false;
 647      }
 648  
 649      if ( isset( $parsed_url['user'] ) || isset( $parsed_url['pass'] ) ) {
 650          return false;
 651      }
 652  
 653      if ( false !== strpbrk( $parsed_url['host'], ':#?[]' ) ) {
 654          return false;
 655      }
 656  
 657      $parsed_home = parse_url( get_option( 'home' ) );
 658      $same_host   = isset( $parsed_home['host'] ) && strtolower( $parsed_home['host'] ) === strtolower( $parsed_url['host'] );
 659      $host        = trim( $parsed_url['host'], '.' );
 660  
 661      if ( ! $same_host ) {
 662          if ( preg_match( '#^(([1-9]?\d|1\d\d|25[0-5]|2[0-4]\d)\.){3}([1-9]?\d|1\d\d|25[0-5]|2[0-4]\d)$#', $host ) ) {
 663              $ip = $host;
 664          } else {
 665              $ip = gethostbyname( $host );
 666              if ( $ip === $host ) { // Error condition for gethostbyname().
 667                  return false;
 668              }
 669          }
 670          if ( $ip ) {
 671              $parts = array_map( 'intval', explode( '.', $ip ) );
 672  
 673              /*
 674               * These IP address ranges are not considered valid external hosts for HTTP requests.
 675               *
 676               * If the host resolves to an IP address in these ranges, the request will be rejected unless the 'http_request_host_is_external' filter allows it.
 677               *
 678               * References:
 679               *
 680               * - IPv4 Special-Purpose Address Space: https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
 681               * - IPv4 Multicast Address Assignments: https://www.rfc-editor.org/rfc/rfc5771.html
 682               */
 683              if ( 127 === $parts[0] || 10 === $parts[0] || 0 === $parts[0]          // 127.0.0.0/8 (loopback), 10.0.0.0/8 (private), 0.0.0.0/8 (this network).
 684                  || ( 172 === $parts[0] && 16 <= $parts[1] && 31 >= $parts[1] )     // 172.16.0.0/12 (private).
 685                  || ( 192 === $parts[0] && 168 === $parts[1] )                      // 192.168.0.0/16 (private).
 686                  || ( 192 === $parts[0] && 0 === $parts[1] && 0 === $parts[2] )     // 192.0.0.0/24 (IETF protocol assignments).
 687                  || ( 192 === $parts[0] && 0 === $parts[1] && 2 === $parts[2] )     // 192.0.2.0/24 (TEST-NET-1).
 688                  || ( 192 === $parts[0] && 88 === $parts[1] && 99 === $parts[2] )   // 192.88.99.0/24 (6to4 relay anycast).
 689                  || ( 198 === $parts[0] && 51 === $parts[1] && 100 === $parts[2] )  // 198.51.100.0/24 (TEST-NET-2).
 690                  || ( 203 === $parts[0] && 0 === $parts[1] && 113 === $parts[2] )   // 203.0.113.0/24 (TEST-NET-3).
 691                  || ( 169 === $parts[0] && 254 === $parts[1] )                      // 169.254.0.0/16 (link-local and cloud metadata).
 692                  || ( 100 === $parts[0] && 64 <= $parts[1] && 127 >= $parts[1] )    // 100.64.0.0/10 (CGNAT).
 693                  || ( 198 === $parts[0] && 18 <= $parts[1] && 19 >= $parts[1] )     // 198.18.0.0/15 (benchmarking).
 694                  || ( 224 <= $parts[0] && 239 >= $parts[0] )                        // 224.0.0.0/4 (multicast).
 695                  || 240 <= $parts[0]                                                // 240.0.0.0/4 (reserved, includes 255.255.255.255 broadcast).
 696              ) {
 697                  // If host appears local, reject unless specifically allowed.
 698                  /**
 699                   * Checks if HTTP request is external or not.
 700                   *
 701                   * Allows to change and allow external requests for the HTTP request.
 702                   *
 703                   * @since 3.6.0
 704                   *
 705                   * @param bool   $external Whether HTTP request is external or not.
 706                   * @param string $host     Host name of the requested URL.
 707                   * @param string $url      Requested URL.
 708                   */
 709                  if ( ! apply_filters( 'http_request_host_is_external', false, $host, $url ) ) {
 710                      return false;
 711                  }
 712              }
 713          }
 714      }
 715  
 716      if ( empty( $parsed_url['port'] ) ) {
 717          return $url;
 718      }
 719  
 720      $port = $parsed_url['port'];
 721  
 722      /**
 723       * Controls the list of ports considered safe in HTTP API.
 724       *
 725       * Allows to change and allow external requests for the HTTP request.
 726       *
 727       * @since 5.9.0
 728       *
 729       * @param int[]  $allowed_ports Array of integers for valid ports. Default allowed ports
 730       *                              are 80, 443, and 8080.
 731       * @param string $host          Host name of the requested URL.
 732       * @param string $url           Requested URL.
 733       */
 734      $allowed_ports = apply_filters( 'http_allowed_safe_ports', array( 80, 443, 8080 ), $host, $url );
 735      if ( is_array( $allowed_ports ) && in_array( $port, $allowed_ports, true ) ) {
 736          return $url;
 737      }
 738  
 739      if ( $parsed_home && $same_host && isset( $parsed_home['port'] ) && $parsed_home['port'] === $port ) {
 740          return $url;
 741      }
 742  
 743      return false;
 744  }
 745  
 746  /**
 747   * Marks allowed redirect hosts safe for HTTP requests as well.
 748   *
 749   * Attached to the {@see 'http_request_host_is_external'} filter.
 750   *
 751   * @since 3.6.0
 752   *
 753   * @param bool   $is_external
 754   * @param string $host
 755   * @return bool
 756   */
 757  function allowed_http_request_hosts( $is_external, $host ) {
 758      if ( ! $is_external && wp_validate_redirect( 'http://' . $host ) ) {
 759          $is_external = true;
 760      }
 761      return $is_external;
 762  }
 763  
 764  /**
 765   * Adds any domain in a multisite installation for safe HTTP requests to the
 766   * allowed list.
 767   *
 768   * Attached to the {@see 'http_request_host_is_external'} filter.
 769   *
 770   * @since 3.6.0
 771   *
 772   * @global wpdb $wpdb WordPress database abstraction object.
 773   *
 774   * @param bool   $is_external
 775   * @param string $host
 776   * @return bool
 777   */
 778  function ms_allowed_http_request_hosts( $is_external, $host ) {
 779      global $wpdb;
 780      static $queried = array();
 781      if ( $is_external ) {
 782          return $is_external;
 783      }
 784      if ( get_network()->domain === $host ) {
 785          return true;
 786      }
 787      if ( isset( $queried[ $host ] ) ) {
 788          return $queried[ $host ];
 789      }
 790      $queried[ $host ] = (bool) $wpdb->get_var( $wpdb->prepare( "SELECT domain FROM $wpdb->blogs WHERE domain = %s LIMIT 1", $host ) );
 791      return $queried[ $host ];
 792  }
 793  
 794  /**
 795   * A wrapper for PHP's parse_url() function that handles consistency in the return values
 796   * across PHP versions.
 797   *
 798   * Across various PHP versions, schemeless URLs containing a ":" in the query
 799   * are being handled inconsistently. This function works around those differences.
 800   *
 801   * @since 4.4.0
 802   * @since 4.7.0 The `$component` parameter was added for parity with PHP's `parse_url()`.
 803   *
 804   * @link https://www.php.net/manual/en/function.parse-url.php
 805   *
 806   * @param string $url       The URL to parse.
 807   * @param int    $component The specific component to retrieve. Use one of the PHP
 808   *                          predefined constants to specify which one.
 809   *                          Defaults to -1 (= return all parts as an array).
 810   * @return mixed False on parse failure; Array of URL components on success;
 811   *               When a specific component has been requested: null if the component
 812   *               doesn't exist in the given URL; a string or - in the case of
 813   *               PHP_URL_PORT - integer when it does. See parse_url()'s return values.
 814   *
 815   * @phpstan-param int<-1, 7> $component
 816   * @phpstan-return (
 817   *     $component is -1
 818   *         ? false|array{
 819   *               scheme?: string,
 820   *               host?: string,
 821   *               port?: int<0, 65535>,
 822   *               user?: string,
 823   *               pass?: string,
 824   *               path?: string,
 825   *               query?: string,
 826   *               fragment?: string,
 827   *           }
 828   *         : (
 829   *             $component is 2
 830   *                 ? int<0, 65535>|null
 831   *                 : string|null
 832   *         )
 833   * )
 834   */
 835  function wp_parse_url( $url, $component = -1 ) {
 836      $to_unset = array();
 837      $url      = (string) $url;
 838  
 839      if ( str_starts_with( $url, '//' ) ) {
 840          $to_unset[] = 'scheme';
 841          $url        = 'placeholder:' . $url;
 842      } elseif ( str_starts_with( $url, '/' ) ) {
 843          $to_unset[] = 'scheme';
 844          $to_unset[] = 'host';
 845          $url        = 'placeholder://placeholder' . $url;
 846      }
 847  
 848      $parts = parse_url( $url );
 849  
 850      if ( false === $parts ) {
 851          // Parsing failure.
 852          return $parts;
 853      }
 854  
 855      // Remove the placeholder values.
 856      foreach ( $to_unset as $key ) {
 857          unset( $parts[ $key ] );
 858      }
 859  
 860      return _get_component_from_parsed_url_array( $parts, $component );
 861  }
 862  
 863  /**
 864   * Retrieves a specific component from a parsed URL array.
 865   *
 866   * @internal
 867   *
 868   * @since 4.7.0
 869   * @access private
 870   *
 871   * @link https://www.php.net/manual/en/function.parse-url.php
 872   *
 873   * @param array|false $url_parts The parsed URL. Can be false if the URL failed to parse.
 874   * @param int         $component The specific component to retrieve. Use one of the PHP
 875   *                               predefined constants to specify which one.
 876   *                               Defaults to -1 (= return all parts as an array).
 877   * @return mixed False on parse failure; Array of URL components on success;
 878   *               When a specific component has been requested: null if the component
 879   *               doesn't exist in the given URL; a string or - in the case of
 880   *               PHP_URL_PORT - integer when it does. See parse_url()'s return values.
 881   *
 882   * @phpstan-param false|array{
 883   *     scheme?: string,
 884   *     host?: string,
 885   *     port?: int<0, 65535>,
 886   *     user?: string,
 887   *     pass?: string,
 888   *     path?: string,
 889   *     query?: string,
 890   *     fragment?: string,
 891   * } $url_parts
 892   * @phpstan-param int<-1, 7> $component
 893   * @phpstan-return (
 894   *     $component is -1
 895   *         ? false|array{
 896   *               scheme?: string,
 897   *               host?: string,
 898   *               port?: int<0, 65535>,
 899   *               user?: string,
 900   *               pass?: string,
 901   *               path?: string,
 902   *               query?: string,
 903   *               fragment?: string,
 904   *           }
 905   *         : (
 906   *             $component is 2
 907   *                 ? int<0, 65535>|null
 908   *                 : string|null
 909   *         )
 910   * )
 911   */
 912  function _get_component_from_parsed_url_array( $url_parts, $component = -1 ) {
 913      if ( -1 === $component ) {
 914          return $url_parts;
 915      }
 916  
 917      $key = _wp_translate_php_url_constant_to_key( $component );
 918      if ( false !== $key && is_array( $url_parts ) && isset( $url_parts[ $key ] ) ) {
 919          return $url_parts[ $key ];
 920      } else {
 921          return null;
 922      }
 923  }
 924  
 925  /**
 926   * Translates a PHP_URL_* constant to the named array keys PHP uses.
 927   *
 928   * @internal
 929   *
 930   * @since 4.7.0
 931   * @access private
 932   *
 933   * @link https://www.php.net/manual/en/url.constants.php
 934   *
 935   * @param int $constant PHP_URL_* constant.
 936   * @return string|false The named key or false.
 937   *
 938   * @phpstan-param int<-1, 7> $constant
 939   * @phpstan-return 'scheme'|'host'|'port'|'user'|'pass'|'path'|'query'|'fragment'|false
 940   */
 941  function _wp_translate_php_url_constant_to_key( $constant ) {
 942      $translation = array(
 943          PHP_URL_SCHEME   => 'scheme',
 944          PHP_URL_HOST     => 'host',
 945          PHP_URL_PORT     => 'port',
 946          PHP_URL_USER     => 'user',
 947          PHP_URL_PASS     => 'pass',
 948          PHP_URL_PATH     => 'path',
 949          PHP_URL_QUERY    => 'query',
 950          PHP_URL_FRAGMENT => 'fragment',
 951      );
 952  
 953      return $translation[ $constant ] ?? false;
 954  }


Generated : Thu Dec 3 08:20:02 2026 Cross-referenced by PHPXref