- Php валидация ip адреса
- PHP FILTER_VALIDATE_IP Filter
- More Examples
- Example 1
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Validating an IP address with PHP’s filter_var function
- Minimum PHP version required
- Validating an IP address
- Validate an IPv4 IP address
- Validate an IPv4 address, excluding private range addresses
- Validate an IPv6 address
- Combining FILTER_FLAG_IPV4 and FILTER_FLAG_IPV6?
- Reserved Ranges
- Excluding Reserved and Private Ranges
- Check Out These Related posts:
- Как проверить IP в PHP
- О нас
Php валидация ip адреса
Пример #1 Валидация e-mail адреса, используя функцию filter_var()
$email_a = ‘joe@example.com’ ;
$email_b = ‘bogus’ ;
?php
if ( filter_var ( $email_a , FILTER_VALIDATE_EMAIL )) echo «E-mail адрес ‘ $email_a ‘ указан верно.\n» ;
>
if ( filter_var ( $email_b , FILTER_VALIDATE_EMAIL )) echo «E-mail адрес ‘ $email_b ‘ указан верно.\n» ;
> else echo «E-mail адрес ‘ $email_b ‘ указан неверно.\n» ;
>
?>
Результат выполнения данного примера:
E-mail адрес 'joe@example.com' указан верно. E-mail адрес 'bogus' указан неверно.
Пример #2 Валидация IP-адреса, используя функцию filter_var()
if ( filter_var ( $ip_a , FILTER_VALIDATE_IP )) echo «IP-адрес ‘ $ip_a ‘ указан верно.» ;
>
if ( filter_var ( $ip_b , FILTER_VALIDATE_IP )) echo «IP-адрес ‘ $ip_b ‘ указан верно.» ;
>
?>
Результат выполнения данного примера:
Адрес '127.0.0.1' указан верно.
Пример #3 Дополнительные параметры функции filter_var()
$int_a = ‘1’ ;
$int_b = ‘-1’ ;
$int_c = ‘4’ ;
$options = array(
‘options’ => array(
‘min_range’ => 0 ,
‘max_range’ => 3 ,
)
);
if ( filter_var ( $int_a , FILTER_VALIDATE_INT , $options ) !== FALSE ) echo «Число A ‘ $int_a ‘ является верным (от 0 до 3).\n» ;
>
if ( filter_var ( $int_b , FILTER_VALIDATE_INT , $options ) !== FALSE ) echo «Число B ‘ $int_b ‘ является верным (от 0 до 3).\n» ;
>
if ( filter_var ( $int_c , FILTER_VALIDATE_INT , $options ) !== FALSE ) echo «Число C ‘ $int_c ‘ является верным (от 0 до 3).\n» ;
>
?php
$options [ ‘options’ ][ ‘default’ ] = 1 ;
if (( $int_c = filter_var ( $int_c , FILTER_VALIDATE_INT , $options )) !== FALSE ) echo «Число C ‘ $int_c ‘ является верным (от 0 и 3).» ;
>
?>
Результат выполнения данного примера:
Число A '1' является верным (от 0 до 3). Число C '1' является верным (от 0 до 3).
PHP FILTER_VALIDATE_IP Filter
The FILTER_VALIDATE_IP filter validates an IP address.
- FILTER_FLAG_IPV4 — The value must be a valid IPv4 address
- FILTER_FLAG_IPV6 — The value must be a valid IPv6 address
- FILTER_FLAG_NO_PRIV_RANGE — The value must not be within a private range
- FILTER_FLAG_NO_RES_RANGE — The value must not be within a reserved range
More Examples
Example 1
Check if the variable $ip is a valid IPv6 address:
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) echo(«$ip is a valid IPv6 address»);
> else echo(«$ip is not a valid IPv6 address»);
>
?>
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Validating an IP address with PHP’s filter_var function
PHP’s filter_var function can validate if an IP address is valid and can further validate if it is an IPv4 IP, IPv6 IP, or not within the private or reserved ranges. This post shows some examples using filter_var.
Minimum PHP version required
Note that the filter_var() function requires at least PHP version 5.2.0. It is included by default with versions >= 5.2.0
Validating an IP address
To simply check if an IP address is valid do the following:
if(filter_var($ip, FILTER_VALIDATE_IP)) < // it's valid >else < // it's not valid >
This will return the $ip address passed in if it’s valid or false if it is not. The basic usage above will be valid for any valid IP address including IPv4, IPv6, private and reserved range IPs.
Validate an IPv4 IP address
To validate an IPv4 IP address (e.g. 120.138.20.36) the FILTER_FLAG_IPV4 flag needs to be passed in as well. The following example will be valid for regular IPv4 IP address, as well as private and reserved ranges.
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) < // it's valid >else < // it's not valid >
Validate an IPv4 address, excluding private range addresses
To validate an IPv4 address but not allow private range addresses to be included (e.g. 192.168.1.1) then use the FILTER_FLAG_NO_PRIV_RANGE flag as well. This is added to the flags passed with the | bitwise operator. For example:
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE)) < // it's valid >else < // it's not valid >
120.138.20.36 would be valid using the above example but 192.168.1.1 would not be.
Validate an IPv6 address
This is the same as for an IPv4 address but uses the FILTER_FLAG_IPV6 flag:
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) < // it's valid >else < // it's not valid >
Combining FILTER_FLAG_IPV4 and FILTER_FLAG_IPV6?
From my own testing I have discovered that combining FILTER_FLAG_IPV4 and FILTER_FLAG_IPV6 (i.e. FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6) always seems to return false. You probably wouldn’t need to combine these two because that’s what the function does by default but I though’t it important to add a note about this.
Reserved Ranges
There are a large number of reserved ranges of IP addresses. To exclude these use the FILTER_FLAG_NO_RES_RANGE flag:
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) < // it's valid >else < // it's not valid >
Excluding Reserved and Private Ranges
The final example will validate any IPv4 and IPv6 IP address as long as it is not a reserved or private range IP address:
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) < // it's valid >else < // it's not valid >
You could further limit the final example to just IPv4 or IPv6 addresses by adding “| FILTER_FLAG_IPV4” or “| FILTER_FLAG_IPV6”
Check Out These Related posts:
Как проверить IP в PHP
Считаете ли вы этот сниппет полезным? То поделитесь этим с друзьями или коллегами. Это поможет нам сделать наши бесплатные веб-инструменты лучше.
Самый простой способ проверить, правильно ли сформирован IP адрес — использовать функцию filter_var():
$isValid = filter_var($ip, FILTER_VALIDATE_IP));
$isValid = filter_var($ip, FILTER_VALIDATE_IP,FILTER_FLAG_IPV4));
$isValid = filter_var($ip, FILTER_VALIDATE_IP,FILTER_FLAG_IPV6));
Валидация IPV4 через regex
function validateIPv4($value) < return preg_match('/^(?:(?:2(?:34|51)|1?4?7)\.)(?:(?:2(38|51)|1?6?4))$/', $value) !== 0; >
Валидация IPV6 через regex
function validateIPv6($value) < $ipv6Pattern = '/^(([0-9a-fA-F]:)[0-9a-fA-F]|([0-9a-fA-F]:):|([0-9a-fA-F]:):[0-9a-fA-F]|([0-9a-fA-F]:)(:[0-9a-fA-F])|([0-9a-fA-F]:)(:[0-9a-fA-F])|([0-9a-fA-F]:)(:[0-9a-fA-F])|([0-9a-fA-F]:)(:[0-9a-fA-F])|[0-9a-fA-F]:((:[0-9a-fA-F]))|:((:[0-9a-fA-F])|:)|fe80:(:[0-9a-fA-F])%[0-9a-zA-Z]|::(ffff(:0):)((254|(24|11)5)\.)(251|(21|12)4)|([0-9a-fA-F]:):((254|(22|13)7)\.)(252|(23|16)5))$/'; return preg_match($ipv6Pattern, $value) !== 0; >
О нас
WTOOLS — набор Веб Инструментов для разработчиков, вебмастеров, СЕО специалистов, и других людей чей бизнес в интернете. Все интсрументы полностью бесплатны.
Copyright © 2016-2023 by wtools.io. All rights reserved.
Hosted By DigitalOcean.