验证值是有效的IP地址
var_dump(filter_var('185.158.24.24', FILTER_VALIDATE_IP)); var_dump(filter_var('2001:0db8:0a0b:12f0:0000:0000:0000:0001', FILTER_VALIDATE_IP)); var_dump(filter_var('192.168.0.1', FILTER_VALIDATE_IP)); var_dump(filter_var('127.0.0.1', FILTER_VALIDATE_IP));
结果:
string(13) "185.158.24.24" string(39) "2001:0db8:0a0b:12f0:0000:0000:0000:0001" string(11) "192.168.0.1" string(9) "127.0.0.1"
验证有效的IPv4 IP地址:
var_dump(filter_var('185.158.24.24', FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)); var_dump(filter_var('2001:0db8:0a0b:12f0:0000:0000:0000:0001', FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)); var_dump(filter_var('192.168.0.1', FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)); var_dump(filter_var('127.0.0.1', FILTER_VALIDATE_IP, FILTER_FLAG_IPV4));
结果:
string(13) "185.158.24.24" bool(false) string(11) "192.168.0.1" string(9) "127.0.0.1"
验证有效的IPv6 IP地址:
var_dump(filter_var('185.158.24.24', FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)); var_dump(filter_var('2001:0db8:0a0b:12f0:0000:0000:0000:0001', FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)); var_dump(filter_var('192.168.0.1', FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)); var_dump(filter_var('127.0.0.1', FILTER_VALIDATE_IP, FILTER_FLAG_IPV6));
结果:
bool(false) string(39) "2001:0db8:0a0b:12f0:0000:0000:0000:0001" bool(false) bool(false)
验证IP地址不在私有范围内:
var_dump(filter_var('185.158.24.24', FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)); var_dump(filter_var('2001:0db8:0a0b:12f0:0000:0000:0000:0001', FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)); var_dump(filter_var('192.168.0.1', FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)); var_dump(filter_var('127.0.0.1', FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE));
结果:
string(13) "185.158.24.24" string(39) "2001:0db8:0a0b:12f0:0000:0000:0000:0001" bool(false) string(9) "127.0.0.1"
验证IP地址不在保留范围内:
var_dump(filter_var('185.158.24.24', FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)); var_dump(filter_var('2001:0db8:0a0b:12f0:0000:0000:0000:0001', FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)); var_dump(filter_var('192.168.0.1', FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)); var_dump(filter_var('127.0.0.1', FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE));
结果:
string(13) "185.158.24.24" bool(false) string(11) "192.168.0.1" bool(false)