wp_http_validate_url

Validate a URL for safe use in the HTTP API.

Description

(false|string) wp_http_validate_url( (string) $url ); 

Returns (false|string)

URL or false on failure.

Parameters (1)

0. $url (string)
The url.

Usage

  1. if ( !function_exists( 'wp_http_validate_url' ) ) { 
  2. require_once ABSPATH . WPINC . '/http.php'; 
  3.  
  4. // The url. 
  5. $url = ''; 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = wp_http_validate_url($url); 
  9.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/http.php  
  1. function wp_http_validate_url( $url ) { 
  2. $original_url = $url; 
  3. $url = wp_kses_bad_protocol( $url, array( 'http', 'https' ) ); 
  4. if ( ! $url || strtolower( $url ) !== strtolower( $original_url ) ) 
  5. return false; 
  6.  
  7. $parsed_url = @parse_url( $url ); 
  8. if ( ! $parsed_url || empty( $parsed_url['host'] ) ) 
  9. return false; 
  10.  
  11. if ( isset( $parsed_url['user'] ) || isset( $parsed_url['pass'] ) ) 
  12. return false; 
  13.  
  14. if ( false !== strpbrk( $parsed_url['host'], ':#?[]' ) ) 
  15. return false; 
  16.  
  17. $parsed_home = @parse_url( get_option( 'home' ) ); 
  18.  
  19. if ( isset( $parsed_home['host'] ) ) { 
  20. $same_host = ( strtolower( $parsed_home['host'] ) === strtolower( $parsed_url['host'] ) || 'localhost' === strtolower( $parsed_url['host'] ) ); 
  21. } else { 
  22. $same_host = false; 
  23.  
  24. if ( ! $same_host ) { 
  25. $host = trim( $parsed_url['host'], '.' ); 
  26. 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 ) ) { 
  27. $ip = $host; 
  28. } else { 
  29. $ip = gethostbyname( $host ); 
  30. if ( $ip === $host ) // Error condition for gethostbyname() 
  31. $ip = false; 
  32. if ( $ip ) { 
  33. $parts = array_map( 'intval', explode( '.', $ip ) ); 
  34. if ( 127 === $parts[0] || 10 === $parts[0] || 0 === $parts[0] 
  35. || ( 172 === $parts[0] && 16 <= $parts[1] && 31 >= $parts[1] ) 
  36. || ( 192 === $parts[0] && 168 === $parts[1] ) 
  37. ) { 
  38. // If host appears local, reject unless specifically allowed. 
  39. /** 
  40. * Check if HTTP request is external or not. 
  41. * Allows to change and allow externalrequestsfor the HTTP request. 
  42. * @since 3.6.0 
  43. * @param bool false Whether HTTP request is external or not. 
  44. * @param string $host IP of the requested host. 
  45. * @param string $url URL of the requested host. 
  46. */ 
  47. if ( ! apply_filters( 'http_request_host_is_external', false, $host, $url ) ) 
  48. return false; 
  49.  
  50. if ( empty( $parsed_url['port'] ) ) 
  51. return $url; 
  52.  
  53. $port = $parsed_url['port']; 
  54. if ( 80 === $port || 443 === $port || 8080 === $port ) 
  55. return $url; 
  56.  
  57. if ( $parsed_home && $same_host && isset( $parsed_home['port'] ) && $parsed_home['port'] === $port ) 
  58. return $url; 
  59.  
  60. return false;