The last topic that I'm going to cover in this tutorial will consist of demonstrating how to utilize the FILTER_VALIDATE_IP filter that you learned in the previous section, but this time for validating IPv6 and private addresses. The following example shows how to perform this first task pretty clearly. Here it is: // example on validating IP address using the FILTER_FLAG_IPV6 argument $ip = '2001:0cb8:25a3:04c1:1324:8a2b:0471:8221'; if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === FALSE) // displays IP is valid { echo 'IP is not valid.'; } else { echo 'IP is valid.'; } There you have it. By specifying the new FILTER_FLAG_IPV6 constant, it's possible to determine if a given IP address fits the requirements of the IPv6 protocol. In addition, the FILTER_VALIDATE_IP filter allows you to validate private and reserved IP addresses as well, and the following code samples demonstrate how to do that. Look at them: // example on validating IP address using the FILTER_FLAG_NO_PRIV_RANGE argument $ip = '192.168.37.1'; if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE) === FALSE) // displays IP is not valid { echo 'IP is not valid.'; } else { echo 'IP is valid.'; } // example on validating IP address using the FILTER_FLAG_NO_RES_RANGE argument $ip = '255.255.255.255'; if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) === FALSE) // displays IP is not valid { echo 'IP is not valid.'; } else { echo 'IP is valid.'; } As you can see above, checking if an IP address belongs to a private or a reserved range is only a matter of using the FILTER_FLAG_NO_PRIV_RANGE and FILTER_FLAG_NO_RES_RANGE constants in the appropriate case. Of course, taking advantage of the functionality of all of the arguments that you saw before, in conjunction with the "filter_var()" function, will let you build powerful functions and class methods that will perform thorough validation of IP addresses. I will definitely leave this project as homework for you. Final thoughts In this seventh episode of the series, you learned how to exploit the functionality offered by the filter extension that comes bundled with PHP 5 for validating both v4 and v6 IP addresses. This process is simple enough that you should not have any major problems incorporating this feature into your own PHP applications. In the next article, things will get even more interesting, since I'm going to discuss how to use the filter extension to sanitize all sorts of strings. Do you want to see how this will be done? Then don't miss the upcoming tutorial!
blog comments powered by Disqus |
|
|
|
|
|
|
|