PHP: IP validation
Posted: Tue Jul 15, 2014 1:10 pm
Hello everyone,
Another simple tutorial for everyone. IP Validation in PHP. What's that you ask? It validates if an IP is actually an IP or not. It is a PHP filter called filter_validate_ip, and it "validates the value as an IP address".
We have two files for this example, index.html and validate.php.
index.html:
validate.php:
There is a lot more you can do with this, also there are flags you can use to validate IPV4 and IPV6 IP Addresses too, the ip you validate must be an IPv4 or IPv6 IP for you to validate it. Just add the flag like this:
or
Hope you liked this short PHP tutorial and of course if you learnt anything or liked the tutorial then +rep, and if you need any help feel free to reply.
Another simple tutorial for everyone. IP Validation in PHP. What's that you ask? It validates if an IP is actually an IP or not. It is a PHP filter called filter_validate_ip, and it "validates the value as an IP address".
We have two files for this example, index.html and validate.php.
index.html:
Code: Select all
Our HTML file is just a form with two fields, submit button and a text field for the IP address. The form posts the data to our PHP file validate.php. <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>IP Validator by SmashApps</title>
</head>
<body>
<form method="post" action="validate.php">
Enter an IP address to validate it</br>
<input type="text" placeholder="IP Address" name="inputIP">
<input type="submit" value="Submit">
</form>
</body>
</html>
validate.php:
Code: Select all
We have a variable that stores our post data from the form (our IP address) and then we use our filter to validate it. If the IP address is not valid (or valid) it will display a message in the browser. <?php
$ipAddress = $_POST['inputIP'];
if(!filter_var($ipAddress, FILTER_VALIDATE_IP))
{
echo "IP Address is not valid";
} else {
echo "IP Addressis valid";
}
echo "</br><a href=\"index.html\">Enter another address</a>";
There is a lot more you can do with this, also there are flags you can use to validate IPV4 and IPV6 IP Addresses too, the ip you validate must be an IPv4 or IPv6 IP for you to validate it. Just add the flag like this:
Code: Select all
($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6))
or
Code: Select all
($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4))
Hope you liked this short PHP tutorial and of course if you learnt anything or liked the tutorial then +rep, and if you need any help feel free to reply.