| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* IP address handler for validating and normalizing IP addresses |
| 5 |
*/ |
| 6 |
class Redirection_IP { |
| 7 |
/** |
| 8 |
* Validated and normalized IP address |
| 9 |
* |
| 10 |
* @var string |
| 11 |
*/ |
| 12 |
private $ip = ''; |
| 13 |
|
| 14 |
/** |
| 15 |
* Constructor. Validates and normalizes an IP address |
| 16 |
* |
| 17 |
* @param string $ip IP address to validate (may be comma-separated list, first value will be used). |
| 18 |
*/ |
| 19 |
public function __construct( $ip = '' ) { |
| 20 |
$ip = sanitize_text_field( $ip ); |
| 21 |
$ip = explode( ',', $ip ); |
| 22 |
$ip = array_shift( $ip ); |
| 23 |
$ip = filter_var( $ip, FILTER_VALIDATE_IP ); |
| 24 |
if ( $ip === false ) { |
| 25 |
return; |
| 26 |
} |
| 27 |
|
| 28 |
// Convert to binary |
| 29 |
// phpcs:ignore |
| 30 |
$ip = @inet_pton( trim( $ip ) ); |
| 31 |
if ( $ip !== false ) { |
| 32 |
// phpcs:ignore |
| 33 |
$ip = @inet_ntop( $ip ); // Convert back to string; |
| 34 |
if ( $ip === false ) { |
| 35 |
return; |
| 36 |
} |
| 37 |
|
| 38 |
$this->ip = $ip; |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* Get the validated IP address |
| 44 |
* |
| 45 |
* @return string Validated IP address, or empty string if invalid. |
| 46 |
*/ |
| 47 |
public function get() { |
| 48 |
return $this->ip; |
| 49 |
} |
| 50 |
} |
| 51 |
|