简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM