PHP: IP validation

1 post Page 1 of 1
Contributors
User avatar
smashapps
Coding Guru
Coding Guru
Posts: 961
Joined: Tue Apr 05, 2011 8:41 am

PHP: IP validation
smashapps
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:
Code: Select all
<!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>
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.

validate.php:
Code: Select all
<?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>";
 
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.

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.
My name is Tom | Visit my blog where I post new content every day! Tom's Daily Blog | MineCraft is awesome!
1 post Page 1 of 1
Return to “Tutorials”