0

I have a simple PHP form that I'd like to improve validation to help fight empty form submissions from bots.

I have the following array that houses input names from another page.

$expected = array('Project-Inquiry','Name','Company-Name','Phone-Number','Email');

I'd like to verify that these elements, in fact, do contain content, as they're already verified with JS on the previous page. JS is only good when it's enabled, so I'd like to add an extra layer of validation here for when it's disabled.

I tried the following:

$expected = array_filter($expected);

if (!empty($expected)) {
// Do Something
}

And I have also tried the following:

$error = false;
foreach($expected as $field) {
    if (empty($_POST[$field])) {
        $error = true;
    }
}
if ($error) {
    // Do Something
}

I seem to be falling short. Any suggestions?

Matt U
  • 46
  • 5

3 Answers3

0

If you want to fight against bots

  1. Create a hidden input that human doesn't see and bots will fill it. You need to check that input before doing anything. If that input filled, it means that form sent by bot not human.

  2. Create a session with current time when you are showing form, when post happening check the time difference. if it is less than 3 sec it's a bot.

  3. use captcha system.

If you want to validate inputs

Don't do validation like what you did on your question. You should try to validate each one of them with proper validation method. for example how you should validate email is completely different from name.

for example do this for email:

$email = (isset($_POST['email']) && is_string($_POST['email']))? trim($_POST['email']) : '';
$email_error = (filter_var($email,FILTER_VALIDATE_EMAIL))? true : false;

for name is different:

$name = (isset($_POST['name']) && is_string($_POST['name']))? trim($_POST['name']) : '';
$name_error = (strlen($name)>20 || strlen($name)<3)? true : false;

You can add more filter to my examples.

ICE
  • 1,667
  • 2
  • 21
  • 43
0

Let your expected data be array be

$expected = ['name', 'email', 'mobile'];

let form post values be $_POST

foreach($_POST as $key => $value) {
     if (empty($value) && in_array($key, $expected)) {
        if ($value=='') {
            echo $key. ' is should not be empty'."<br/>";
           }   
    }
}

you can get result as expected

HTML FORM

<form action="" method="post">
Name    <input type="text" name="name"><br>
email   <input type="text" name="email"><br>
mobile<input type="text" name="mobile">
    <input type="submit" value="Submit">
</form>
jvk
  • 2,133
  • 3
  • 19
  • 28
0

Have you considered about using a library to validate?

I recommend you to use https://laravel.com/docs/5.5/validation, so you can validate more complex rules also, and it is very clear.