[ 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   * Retrieve 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 is validated to avoid redirection and request forgery attacks.
  34   *
  35   * @since 3.6.0
  36   *
  37   * @see wp_remote_request() For more information on the response array format.
  38   * @see WP_Http::request() For default arguments information.
  39   *
  40   * @param string $url  URL to retrieve.
  41   * @param array  $args Optional. Request arguments. Default empty array.
  42   *                     See WP_Http::request() for information on accepted arguments.
  43   * @return array|WP_Error The response or WP_Error on failure.
  44   */
  45  function wp_safe_remote_request( $url, $args = array() ) {
  46      $args['reject_unsafe_urls'] = true;
  47      $http                       = _wp_http_get_object();
  48      return $http->request( $url, $args );
  49  }
  50  
  51  /**
  52   * Retrieve the raw response from a safe HTTP request using the GET method.
  53   *
  54   * This function is ideal when the HTTP request is being made to an arbitrary
  55   * URL. The URL is validated to avoid redirection and request forgery attacks.
  56   *
  57   * @since 3.6.0
  58   *
  59   * @see wp_remote_request() For more information on the response array format.
  60   * @see WP_Http::request() For default arguments information.
  61   *
  62   * @param string $url  URL to retrieve.
  63   * @param array  $args Optional. Request arguments. Default empty array.
  64   *                     See WP_Http::request() for information on accepted arguments.
  65   * @return array|WP_Error The response or WP_Error on failure.
  66   */
  67  function wp_safe_remote_get( $url, $args = array() ) {
  68      $args['reject_unsafe_urls'] = true;
  69      $http                       = _wp_http_get_object();
  70      return $http->get( $url, $args );
  71  }
  72  
  73  /**
  74   * Retrieve the raw response from a safe HTTP request using the POST method.
  75   *
  76   * This function is ideal when the HTTP request is being made to an arbitrary
  77   * URL. The URL is validated to avoid redirection and request forgery attacks.
  78   *
  79   * @since 3.6.0
  80   *
  81   * @see wp_remote_request() For more information on the response array format.
  82   * @see WP_Http::request() For default arguments information.
  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   */
  89  function wp_safe_remote_post( $url, $args = array() ) {
  90      $args['reject_unsafe_urls'] = true;
  91      $http                       = _wp_http_get_object();
  92      return $http->post( $url, $args );
  93  }
  94  
  95  /**
  96   * Retrieve the raw response from a safe HTTP request using the HEAD method.
  97   *
  98   * This function is ideal when the HTTP request is being made to an arbitrary
  99   * URL. The URL is validated to avoid redirection and request forgery attacks.
 100   *
 101   * @since 3.6.0
 102   *
 103   * @see wp_remote_request() For more information on the response array format.
 104   * @see WP_Http::request() For default arguments information.
 105   *
 106   * @param string $url  URL to retrieve.
 107   * @param array  $args Optional. Request arguments. Default empty array.
 108   *                     See WP_Http::request() for information on accepted arguments.
 109   * @return array|WP_Error The response or WP_Error on failure.
 110   */
 111  function wp_safe_remote_head( $url, $args = array() ) {
 112      $args['reject_unsafe_urls'] = true;
 113      $http                       = _wp_http_get_object();
 114      return $http->head( $url, $args );
 115  }
 116  
 117  /**
 118   * Performs an HTTP request and returns its response.
 119   *
 120   * There are other API functions available which abstract away the HTTP method:
 121   *
 122   *  - Default 'GET'  for wp_remote_get()
 123   *  - Default 'POST' for wp_remote_post()
 124   *  - Default 'HEAD' for wp_remote_head()
 125   *
 126   * @since 2.7.0
 127   *
 128   * @see WP_Http::request() For information on default arguments.
 129   *
 130   * @param string $url  URL to retrieve.
 131   * @param array  $args Optional. Request arguments. Default empty array.
 132   *                     See WP_Http::request() for information on accepted arguments.
 133   * @return array|WP_Error {
 134   *     The response array or a WP_Error on failure.
 135   *
 136   *     @type string[]                       $headers       Array of response headers keyed by their name.
 137   *     @type string                         $body          Response body.
 138   *     @type array                          $response      {
 139   *         Data about the HTTP response.
 140   *
 141   *         @type int|false    $code    HTTP response code.
 142   *         @type string|false $message HTTP response message.
 143   *     }
 144   *     @type WP_HTTP_Cookie[]               $cookies       Array of response cookies.
 145   *     @type WP_HTTP_Requests_Response|null $http_response Raw HTTP response object.
 146   * }
 147   */
 148  function wp_remote_request( $url, $args = array() ) {
 149      $http = _wp_http_get_object();
 150      return $http->request( $url, $args );
 151  }
 152  
 153  /**
 154   * Performs an HTTP request using the GET method and returns its response.
 155   *
 156   * @since 2.7.0
 157   *
 158   * @see wp_remote_request() For more information on the response array format.
 159   * @see WP_Http::request() For default arguments information.
 160   *
 161   * @param string $url  URL to retrieve.
 162   * @param array  $args Optional. Request arguments. Default empty array.
 163   *                     See WP_Http::request() for information on accepted arguments.
 164   * @return array|WP_Error The response or WP_Error on failure.
 165   */
 166  function wp_remote_get( $url, $args = array() ) {
 167      $http = _wp_http_get_object();
 168      return $http->get( $url, $args );
 169  }
 170  
 171  /**
 172   * Performs an HTTP request using the POST method and returns its response.
 173   *
 174   * @since 2.7.0
 175   *
 176   * @see wp_remote_request() For more information on the response array format.
 177   * @see WP_Http::request() For default arguments information.
 178   *
 179   * @param string $url  URL to retrieve.
 180   * @param array  $args Optional. Request arguments. Default empty array.
 181   *                     See WP_Http::request() for information on accepted arguments.
 182   * @return array|WP_Error The response or WP_Error on failure.
 183   */
 184  function wp_remote_post( $url, $args = array() ) {
 185      $http = _wp_http_get_object();
 186      return $http->post( $url, $args );
 187  }
 188  
 189  /**
 190   * Performs an HTTP request using the HEAD method and returns its response.
 191   *
 192   * @since 2.7.0
 193   *
 194   * @see wp_remote_request() For more information on the response array format.
 195   * @see WP_Http::request() For default arguments information.
 196   *
 197   * @param string $url  URL to retrieve.
 198   * @param array  $args Optional. Request arguments. Default empty array.
 199   *                     See WP_Http::request() for information on accepted arguments.
 200   * @return array|WP_Error The response or WP_Error on failure.
 201   */
 202  function wp_remote_head( $url, $args = array() ) {
 203      $http = _wp_http_get_object();
 204      return $http->head( $url, $args );
 205  }
 206  
 207  /**
 208   * Retrieve only the headers from the raw response.
 209   *
 210   * @since 2.7.0
 211   * @since 4.6.0 Return value changed from an array to an WpOrg\Requests\Utility\CaseInsensitiveDictionary instance.
 212   *
 213   * @see \WpOrg\Requests\Utility\CaseInsensitiveDictionary
 214   *
 215   * @param array|WP_Error $response HTTP response.
 216   * @return \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array The headers of the response, or empty array
 217   *                                                                 if incorrect parameter given.
 218   */
 219  function wp_remote_retrieve_headers( $response ) {
 220      if ( is_wp_error( $response ) || ! isset( $response['headers'] ) ) {
 221          return array();
 222      }
 223  
 224      return $response['headers'];
 225  }
 226  
 227  /**
 228   * Retrieve a single header by name from the raw response.
 229   *
 230   * @since 2.7.0
 231   *
 232   * @param array|WP_Error $response HTTP response.
 233   * @param string         $header   Header name to retrieve value from.
 234   * @return array|string The header(s) value(s). Array if multiple headers with the same name are retrieved.
 235   *                      Empty string if incorrect parameter given, or if the header doesn't exist.
 236   */
 237  function wp_remote_retrieve_header( $response, $header ) {
 238      if ( is_wp_error( $response ) || ! isset( $response['headers'] ) ) {
 239          return '';
 240      }
 241  
 242      if ( isset( $response['headers'][ $header ] ) ) {
 243          return $response['headers'][ $header ];
 244      }
 245  
 246      return '';
 247  }
 248  
 249  /**
 250   * Retrieve only the response code from the raw response.
 251   *
 252   * Will return an empty string if incorrect parameter value is given.
 253   *
 254   * @since 2.7.0
 255   *
 256   * @param array|WP_Error $response HTTP response.
 257   * @return int|string The response code as an integer. Empty string if incorrect parameter given.
 258   */
 259  function wp_remote_retrieve_response_code( $response ) {
 260      if ( is_wp_error( $response ) || ! isset( $response['response'] ) || ! is_array( $response['response'] ) ) {
 261          return '';
 262      }
 263  
 264      return $response['response']['code'];
 265  }
 266  
 267  /**
 268   * Retrieve only the response message from the raw response.
 269   *
 270   * Will return an empty string if incorrect parameter value is given.
 271   *
 272   * @since 2.7.0
 273   *
 274   * @param array|WP_Error $response HTTP response.
 275   * @return string The response message. Empty string if incorrect parameter given.
 276   */
 277  function wp_remote_retrieve_response_message( $response ) {
 278      if ( is_wp_error( $response ) || ! isset( $response['response'] ) || ! is_array( $response['response'] ) ) {
 279          return '';
 280      }
 281  
 282      return $response['response']['message'];
 283  }
 284  
 285  /**
 286   * Retrieve only the body from the raw response.
 287   *
 288   * @since 2.7.0
 289   *
 290   * @param array|WP_Error $response HTTP response.
 291   * @return string The body of the response. Empty string if no body or incorrect parameter given.
 292   */
 293  function wp_remote_retrieve_body( $response ) {
 294      if ( is_wp_error( $response ) || ! isset( $response['body'] ) ) {
 295          return '';
 296      }
 297  
 298      return $response['body'];
 299  }
 300  
 301  /**
 302   * Retrieve only the cookies from the raw response.
 303   *
 304   * @since 4.4.0
 305   *
 306   * @param array|WP_Error $response HTTP response.
 307   * @return WP_Http_Cookie[] An array of `WP_Http_Cookie` objects from the response.
 308   *                          Empty array if there are none, or the response is a WP_Error.
 309   */
 310  function wp_remote_retrieve_cookies( $response ) {
 311      if ( is_wp_error( $response ) || empty( $response['cookies'] ) ) {
 312          return array();
 313      }
 314  
 315      return $response['cookies'];
 316  }
 317  
 318  /**
 319   * Retrieve a single cookie by name from the raw response.
 320   *
 321   * @since 4.4.0
 322   *
 323   * @param array|WP_Error $response HTTP response.
 324   * @param string         $name     The name of the cookie to retrieve.
 325   * @return WP_Http_Cookie|string The `WP_Http_Cookie` object, or empty string
 326   *                               if the cookie is not present in the response.
 327   */
 328  function wp_remote_retrieve_cookie( $response, $name ) {
 329      $cookies = wp_remote_retrieve_cookies( $response );
 330  
 331      if ( empty( $cookies ) ) {
 332          return '';
 333      }
 334  
 335      foreach ( $cookies as $cookie ) {
 336          if ( $cookie->name === $name ) {
 337              return $cookie;
 338          }
 339      }
 340  
 341      return '';
 342  }
 343  
 344  /**
 345   * Retrieve a single cookie's value by name from the raw response.
 346   *
 347   * @since 4.4.0
 348   *
 349   * @param array|WP_Error $response HTTP response.
 350   * @param string         $name     The name of the cookie to retrieve.
 351   * @return string The value of the cookie, or empty string
 352   *                if the cookie is not present in the response.
 353   */
 354  function wp_remote_retrieve_cookie_value( $response, $name ) {
 355      $cookie = wp_remote_retrieve_cookie( $response, $name );
 356  
 357      if ( ! ( $cookie instanceof WP_Http_Cookie ) ) {
 358          return '';
 359      }
 360  
 361      return $cookie->value;
 362  }
 363  
 364  /**
 365   * Determines if there is an HTTP Transport that can process this request.
 366   *
 367   * @since 3.2.0
 368   *
 369   * @param array  $capabilities Array of capabilities to test or a wp_remote_request() $args array.
 370   * @param string $url          Optional. If given, will check if the URL requires SSL and adds
 371   *                             that requirement to the capabilities array.
 372   *
 373   * @return bool
 374   */
 375  function wp_http_supports( $capabilities = array(), $url = null ) {
 376      $http = _wp_http_get_object();
 377  
 378      $capabilities = wp_parse_args( $capabilities );
 379  
 380      $count = count( $capabilities );
 381  
 382      // If we have a numeric $capabilities array, spoof a wp_remote_request() associative $args array.
 383      if ( $count && count( array_filter( array_keys( $capabilities ), 'is_numeric' ) ) === $count ) {
 384          $capabilities = array_combine( array_values( $capabilities ), array_fill( 0, $count, true ) );
 385      }
 386  
 387      if ( $url && ! isset( $capabilities['ssl'] ) ) {
 388          $scheme = parse_url( $url, PHP_URL_SCHEME );
 389          if ( 'https' === $scheme || 'ssl' === $scheme ) {
 390              $capabilities['ssl'] = true;
 391          }
 392      }
 393  
 394      return (bool) $http->_get_first_available_transport( $capabilities );
 395  }
 396  
 397  /**
 398   * Get the HTTP Origin of the current request.
 399   *
 400   * @since 3.4.0
 401   *
 402   * @return string URL of the origin. Empty string if no origin.
 403   */
 404  function get_http_origin() {
 405      $origin = '';
 406      if ( ! empty( $_SERVER['HTTP_ORIGIN'] ) ) {
 407          $origin = $_SERVER['HTTP_ORIGIN'];
 408      }
 409  
 410      /**
 411       * Change the origin of an HTTP request.
 412       *
 413       * @since 3.4.0
 414       *
 415       * @param string $origin The original origin for the request.
 416       */
 417      return apply_filters( 'http_origin', $origin );
 418  }
 419  
 420  /**
 421   * Retrieve list of allowed HTTP origins.
 422   *
 423   * @since 3.4.0
 424   *
 425   * @return string[] Array of origin URLs.
 426   */
 427  function get_allowed_http_origins() {
 428      $admin_origin = parse_url( admin_url() );
 429      $home_origin  = parse_url( home_url() );
 430  
 431      // @todo Preserve port?
 432      $allowed_origins = array_unique(
 433          array(
 434              'http://' . $admin_origin['host'],
 435              'https://' . $admin_origin['host'],
 436              'http://' . $home_origin['host'],
 437              'https://' . $home_origin['host'],
 438          )
 439      );
 440  
 441      /**
 442       * Change the origin types allowed for HTTP requests.
 443       *
 444       * @since 3.4.0
 445       *
 446       * @param string[] $allowed_origins {
 447       *     Array of default allowed HTTP origins.
 448       *
 449       *     @type string $0 Non-secure URL for admin origin.
 450       *     @type string $1 Secure URL for admin origin.
 451       *     @type string $2 Non-secure URL for home origin.
 452       *     @type string $3 Secure URL for home origin.
 453       * }
 454       */
 455      return apply_filters( 'allowed_http_origins', $allowed_origins );
 456  }
 457  
 458  /**
 459   * Determines if the HTTP origin is an authorized one.
 460   *
 461   * @since 3.4.0
 462   *
 463   * @param string|null $origin Origin URL. If not provided, the value of get_http_origin() is used.
 464   * @return string Origin URL if allowed, empty string if not.
 465   */
 466  function is_allowed_http_origin( $origin = null ) {
 467      $origin_arg = $origin;
 468  
 469      if ( null === $origin ) {
 470          $origin = get_http_origin();
 471      }
 472  
 473      if ( $origin && ! in_array( $origin, get_allowed_http_origins(), true ) ) {
 474          $origin = '';
 475      }
 476  
 477      /**
 478       * Change the allowed HTTP origin result.
 479       *
 480       * @since 3.4.0
 481       *
 482       * @param string $origin     Origin URL if allowed, empty string if not.
 483       * @param string $origin_arg Original origin string passed into is_allowed_http_origin function.
 484       */
 485      return apply_filters( 'allowed_http_origin', $origin, $origin_arg );
 486  }
 487  
 488  /**
 489   * Send Access-Control-Allow-Origin and related headers if the current request
 490   * is from an allowed origin.
 491   *
 492   * If the request is an OPTIONS request, the script exits with either access
 493   * control headers sent, or a 403 response if the origin is not allowed. For
 494   * other request methods, you will receive a return value.
 495   *
 496   * @since 3.4.0
 497   *
 498   * @return string|false Returns the origin URL if headers are sent. Returns false
 499   *                      if headers are not sent.
 500   */
 501  function send_origin_headers() {
 502      $origin = get_http_origin();
 503  
 504      if ( is_allowed_http_origin( $origin ) ) {
 505          header( 'Access-Control-Allow-Origin: ' . $origin );
 506          header( 'Access-Control-Allow-Credentials: true' );
 507          if ( 'OPTIONS' === $_SERVER['REQUEST_METHOD'] ) {
 508              exit;
 509          }
 510          return $origin;
 511      }
 512  
 513      if ( 'OPTIONS' === $_SERVER['REQUEST_METHOD'] ) {
 514          status_header( 403 );
 515          exit;
 516      }
 517  
 518      return false;
 519  }
 520  
 521  /**
 522   * Validate a URL for safe use in the HTTP API.
 523   *
 524   * @since 3.5.2
 525   *
 526   * @param string $url Request URL.
 527   * @return string|false URL or false on failure.
 528   */
 529  function wp_http_validate_url( $url ) {
 530      if ( ! is_string( $url ) || '' === $url || is_numeric( $url ) ) {
 531          return false;
 532      }
 533  
 534      $original_url = $url;
 535      $url          = wp_kses_bad_protocol( $url, array( 'http', 'https' ) );
 536      if ( ! $url || strtolower( $url ) !== strtolower( $original_url ) ) {
 537          return false;
 538      }
 539  
 540      $parsed_url = parse_url( $url );
 541      if ( ! $parsed_url || empty( $parsed_url['host'] ) ) {
 542          return false;
 543      }
 544  
 545      if ( isset( $parsed_url['user'] ) || isset( $parsed_url['pass'] ) ) {
 546          return false;
 547      }
 548  
 549      if ( false !== strpbrk( $parsed_url['host'], ':#?[]' ) ) {
 550          return false;
 551      }
 552  
 553      $parsed_home = parse_url( get_option( 'home' ) );
 554      $same_host   = isset( $parsed_home['host'] ) && strtolower( $parsed_home['host'] ) === strtolower( $parsed_url['host'] );
 555      $host        = trim( $parsed_url['host'], '.' );
 556  
 557      if ( ! $same_host ) {
 558          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 ) ) {
 559              $ip = $host;
 560          } else {
 561              $ip = gethostbyname( $host );
 562              if ( $ip === $host ) { // Error condition for gethostbyname().
 563                  return false;
 564              }
 565          }
 566          if ( $ip ) {
 567              $parts = array_map( 'intval', explode( '.', $ip ) );
 568              if ( 127 === $parts[0] || 10 === $parts[0] || 0 === $parts[0]
 569                  || ( 172 === $parts[0] && 16 <= $parts[1] && 31 >= $parts[1] )
 570                  || ( 192 === $parts[0] && 168 === $parts[1] )
 571              ) {
 572                  // If host appears local, reject unless specifically allowed.
 573                  /**
 574                   * Check if HTTP request is external or not.
 575                   *
 576                   * Allows to change and allow external requests for the HTTP request.
 577                   *
 578                   * @since 3.6.0
 579                   *
 580                   * @param bool   $external Whether HTTP request is external or not.
 581                   * @param string $host     Host name of the requested URL.
 582                   * @param string $url      Requested URL.
 583                   */
 584                  if ( ! apply_filters( 'http_request_host_is_external', false, $host, $url ) ) {
 585                      return false;
 586                  }
 587              }
 588          }
 589      }
 590  
 591      if ( empty( $parsed_url['port'] ) ) {
 592          return $url;
 593      }
 594  
 595      $port = $parsed_url['port'];
 596  
 597      /**
 598       * Controls the list of ports considered safe in HTTP API.
 599       *
 600       * Allows to change and allow external requests for the HTTP request.
 601       *
 602       * @since 5.9.0
 603       *
 604       * @param int[]  $allowed_ports Array of integers for valid ports.
 605       * @param string $host          Host name of the requested URL.
 606       * @param string $url           Requested URL.
 607       */
 608      $allowed_ports = apply_filters( 'http_allowed_safe_ports', array( 80, 443, 8080 ), $host, $url );
 609      if ( is_array( $allowed_ports ) && in_array( $port, $allowed_ports, true ) ) {
 610          return $url;
 611      }
 612  
 613      if ( $parsed_home && $same_host && isset( $parsed_home['port'] ) && $parsed_home['port'] === $port ) {
 614          return $url;
 615      }
 616  
 617      return false;
 618  }
 619  
 620  /**
 621   * Mark allowed redirect hosts safe for HTTP requests as well.
 622   *
 623   * Attached to the {@see 'http_request_host_is_external'} filter.
 624   *
 625   * @since 3.6.0
 626   *
 627   * @param bool   $is_external
 628   * @param string $host
 629   * @return bool
 630   */
 631  function allowed_http_request_hosts( $is_external, $host ) {
 632      if ( ! $is_external && wp_validate_redirect( 'http://' . $host ) ) {
 633          $is_external = true;
 634      }
 635      return $is_external;
 636  }
 637  
 638  /**
 639   * Adds any domain in a multisite installation for safe HTTP requests to the
 640   * allowed list.
 641   *
 642   * Attached to the {@see 'http_request_host_is_external'} filter.
 643   *
 644   * @since 3.6.0
 645   *
 646   * @global wpdb $wpdb WordPress database abstraction object.
 647   *
 648   * @param bool   $is_external
 649   * @param string $host
 650   * @return bool
 651   */
 652  function ms_allowed_http_request_hosts( $is_external, $host ) {
 653      global $wpdb;
 654      static $queried = array();
 655      if ( $is_external ) {
 656          return $is_external;
 657      }
 658      if ( get_network()->domain === $host ) {
 659          return true;
 660      }
 661      if ( isset( $queried[ $host ] ) ) {
 662          return $queried[ $host ];
 663      }
 664      $queried[ $host ] = (bool) $wpdb->get_var( $wpdb->prepare( "SELECT domain FROM $wpdb->blogs WHERE domain = %s LIMIT 1", $host ) );
 665      return $queried[ $host ];
 666  }
 667  
 668  /**
 669   * A wrapper for PHP's parse_url() function that handles consistency in the return values
 670   * across PHP versions.
 671   *
 672   * PHP 5.4.7 expanded parse_url()'s ability to handle non-absolute URLs, including
 673   * schemeless and relative URLs with "://" in the path. This function works around
 674   * those limitations providing a standard output on PHP 5.2~5.4+.
 675   *
 676   * Secondly, across various PHP versions, schemeless URLs containing a ":" in the query
 677   * are being handled inconsistently. This function works around those differences as well.
 678   *
 679   * @since 4.4.0
 680   * @since 4.7.0 The `$component` parameter was added for parity with PHP's `parse_url()`.
 681   *
 682   * @link https://www.php.net/manual/en/function.parse-url.php
 683   *
 684   * @param string $url       The URL to parse.
 685   * @param int    $component The specific component to retrieve. Use one of the PHP
 686   *                          predefined constants to specify which one.
 687   *                          Defaults to -1 (= return all parts as an array).
 688   * @return mixed False on parse failure; Array of URL components on success;
 689   *               When a specific component has been requested: null if the component
 690   *               doesn't exist in the given URL; a string or - in the case of
 691   *               PHP_URL_PORT - integer when it does. See parse_url()'s return values.
 692   */
 693  function wp_parse_url( $url, $component = -1 ) {
 694      $to_unset = array();
 695      $url      = (string) $url;
 696  
 697      if ( str_starts_with( $url, '//' ) ) {
 698          $to_unset[] = 'scheme';
 699          $url        = 'placeholder:' . $url;
 700      } elseif ( str_starts_with( $url, '/' ) ) {
 701          $to_unset[] = 'scheme';
 702          $to_unset[] = 'host';
 703          $url        = 'placeholder://placeholder' . $url;
 704      }
 705  
 706      $parts = parse_url( $url );
 707  
 708      if ( false === $parts ) {
 709          // Parsing failure.
 710          return $parts;
 711      }
 712  
 713      // Remove the placeholder values.
 714      foreach ( $to_unset as $key ) {
 715          unset( $parts[ $key ] );
 716      }
 717  
 718      return _get_component_from_parsed_url_array( $parts, $component );
 719  }
 720  
 721  /**
 722   * Retrieve a specific component from a parsed URL array.
 723   *
 724   * @internal
 725   *
 726   * @since 4.7.0
 727   * @access private
 728   *
 729   * @link https://www.php.net/manual/en/function.parse-url.php
 730   *
 731   * @param array|false $url_parts The parsed URL. Can be false if the URL failed to parse.
 732   * @param int         $component The specific component to retrieve. Use one of the PHP
 733   *                               predefined constants to specify which one.
 734   *                               Defaults to -1 (= return all parts as an array).
 735   * @return mixed False on parse failure; Array of URL components on success;
 736   *               When a specific component has been requested: null if the component
 737   *               doesn't exist in the given URL; a string or - in the case of
 738   *               PHP_URL_PORT - integer when it does. See parse_url()'s return values.
 739   */
 740  function _get_component_from_parsed_url_array( $url_parts, $component = -1 ) {
 741      if ( -1 === $component ) {
 742          return $url_parts;
 743      }
 744  
 745      $key = _wp_translate_php_url_constant_to_key( $component );
 746      if ( false !== $key && is_array( $url_parts ) && isset( $url_parts[ $key ] ) ) {
 747          return $url_parts[ $key ];
 748      } else {
 749          return null;
 750      }
 751  }
 752  
 753  /**
 754   * Translate a PHP_URL_* constant to the named array keys PHP uses.
 755   *
 756   * @internal
 757   *
 758   * @since 4.7.0
 759   * @access private
 760   *
 761   * @link https://www.php.net/manual/en/url.constants.php
 762   *
 763   * @param int $constant PHP_URL_* constant.
 764   * @return string|false The named key or false.
 765   */
 766  function _wp_translate_php_url_constant_to_key( $constant ) {
 767      $translation = array(
 768          PHP_URL_SCHEME   => 'scheme',
 769          PHP_URL_HOST     => 'host',
 770          PHP_URL_PORT     => 'port',
 771          PHP_URL_USER     => 'user',
 772          PHP_URL_PASS     => 'pass',
 773          PHP_URL_PATH     => 'path',
 774          PHP_URL_QUERY    => 'query',
 775          PHP_URL_FRAGMENT => 'fragment',
 776      );
 777  
 778      if ( isset( $translation[ $constant ] ) ) {
 779          return $translation[ $constant ];
 780      } else {
 781          return false;
 782      }
 783  }


Generated : Thu Apr 25 08:20:02 2024 Cross-referenced by PHPXref