In reality, checking for well-formatted IP addresses with the filter extension is a process reduced to using a brand new filter, not surprisingly called FILTER_VALIDATE_IP. As you'll see in a moment, it allows you to not only determine if a specified IP address is valid, but permits you to perform this process utilizing both IPv4 and IPv6 protocols. But first, let me show you how to do a basic validation on a badly-formatted IP address by means of the aforementioned filter. Take a look at the following example, please:
// example on validating IP address $ip = '192.168.37'; if(filter_var($ip, FILTER_VALIDATE_IP) === FALSE) // displays IP is valid. { echo 'IP is not valid.'; } else { echo 'IP is valid.'; } That was pretty simple to grasp, wasn't it? As shown above, the "filter_var()" function has been used in conjunction with the FILTER_VALIDATE_IP filter to validate an incorrect IP address. The example itself is rather trivial, but it shows in a nutshell how to accomplish this task very quickly. Moving forward, imagine for a moment that you need to determine if an IP address sticks to the IPv4 protocol. In that case, it's time to use an additional argument called FILTER_FLAG_IPV4, which must be specified in the following way: // example on validating IP address using the FILTER_FLAG_IPV4 argument $ip = '192.168.37'; if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === FALSE) // displays IP is not valid { echo 'IP is not valid.'; } else { echo 'IP is valid.'; }
Again, I decided to keep the above example very simple, so you can understand how the FILTER_FLAG_IPV4 option works. In this case, the supplied IP address has been incorrectly formatted on purpose, but you may want to create more complex scripts that check for IPv4-compliant IP addresses. All in all, at this stage you hopefully grasped the logic that stands behind validating IPv4 addresses. However, as you know the Internet is running out of available IP addresses due to its tremendous growth. Therefore, in the last section of this article I'm going to show how to use the FILTER_VALIDATE_IP filter for validating IPv6-compliant and private IP addresses. As usual, to see how this will be done, click on the link below and read the segment to come.
blog comments powered by Disqus |
|
|
|
|
|
|
|