GrizPwnz GrizPwnz - 2 months ago 17
HTML Question

PHP and HTML form only allow IP address to be posted

I'm working on an basic HTML form like the one below.

<form action="#" method="post" enctype="multipart/form-data">
<input name="IP" type="text" />
<input type="submit" name="submit" value="Submit">
</form>


And a basic PHP script which will post all data in a TXT document like the one below as well.

$var = $_POST['IP'];
file_put_contents("/example/secretfile.txt", $var . "\n", FILE_APPEND);
exit();


Is there a way to restrict what a user is posting into the HTML form and have PHP validate that the only thing posted is an IP address? I don't want users to be able to post anything besides an IP. The IP does not have to be real or connect to anything. I'm quite new working with PHP so I don't know of a way to do this.

Answer

You can use FILTER_VALIDATE_IP:

$var = $_POST['IP'];
if (filter_var($var, FILTER_VALIDATE_IP) === false) die('This is not a valid IP: ' . $var);
file_put_contents("/example/secretfile.txt", $var . "\n", FILE_APPEND);
exit();

See there for the possible flags (for example, whether IPv4 and IPv6 are accepted, etc.): http://php.net/manual/en/filter.filters.validate.php