Skip to content
Advertisement

Allow only certain inputs to be POSTed

My web application has three possible input fields, two of which are required and one of which are optional. They are $_POST[‘name’] (required), $_POST[‘message’] (required), and $_POST[‘identity’] (optional).

In order to stop spambots from posting, I thought about making a “honeypot” of various fake inputs that a spambot might use (e.g. $_POST[‘username’], $_POST[‘url’]). If some connection were to POST to these, the script would die on them. I could make something like this pretty easily, but the size of my script is a major concern and specifying dozens of honeypot inputs would require more space than I am willing to use.

Instead, I think it makes more sense in my case to have a “reverse honeypot,” i.e. have the script die if anything except the three true input fields is POSTed. But I don’t know a technique for that, and I don’t know if it would cause other problems.

Is there a way for me to specify in PHP that the script should die if anything other than $_POST[‘name’], $_POST[‘message’], and $_POST[‘identity’] is sent? Would doing this cause problems I have not foreseen?

Advertisement

Answer

Use array_keys() to get all the keys of the $_POST array. Subtract the ones that are allowed, and check if there are any keys remaining.

$allowed_fields = ["name", "message", "identity"];
if (!empty(array_diff(array_keys($_POST), $allowed_fields))) {
    die("You're a spammer!");
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement