Stopping empty form submission PHP

前端 未结 4 1285
一整个雨季
一整个雨季 2021-01-28 05:00

I have been trying to implement server validation to prevent blank emails in my contact us page, but I am not sure on how to do it in PHP, here is my code:



        
相关标签:
4条回答
  • 2021-01-28 05:09

    Try to put a submit input <input type="submit" name="sub" value="Submited"> inside your form when it's clicked.

    <?php
    
    if (isset($_POST['sub']) {
      $field_name = $_POST['cf_name'];
      $field_email = $_POST['cf_email'];
      $field_tel = $_POST['cf_tel'];
      $field_message = $_POST['cf_message'];
      if (empty($field_name) && ....)
      {
         exit('Field name is empty');
      }
      .....
    
    0 讨论(0)
  • 2021-01-28 05:13

    just test the variable for "emptiness" and exit early. Something like this:

    if(empty($field_email)) {
        // maybe show the user a reason why this was rejected...
        return;
    }
    

    You probably want to do this for just about all the input fields.

    In addition, you can use JavaScript (jQuery has some nice plugins) to prevent the user from submitting invalid data in the first place. This won't remove the need to do it server side (since they can just disable JS, or someone malicious might intentionally bypass this measure), but it can make it a more user friendly experience.

    0 讨论(0)
  • 2021-01-28 05:17

    Before your $mail_to..

    You can validate the _POST/_GET first on server side.

    <?php
    if (empty($field_name) && empty($field_email) && empty($field_tel) && empty($field_message)) {
        echo 'Please correct the fields';
        return false;
    }
    ?>
    

    Alternatively, you can validate first on the client-side. It will save you time and resources.

    0 讨论(0)
  • 2021-01-28 05:20

    You can use filter for this; since you're using the passed email address as part of the mail() operation, it's best to also validate:

    $fields = filter_input_array(INPUT_POST, array(
        'name' => FILTER_UNSAFE_RAW,
        'email' => FILTER_VALIDATE_EMAIL,
        'tel' => FILTER_UNSAFE_RAW,
        'message' => FILTER_UNSAFE_RAW,
    ));
    
    // check for missing fields
    if (null === $fields || in_array(null, $fields, true)) {
      // some or all fields missing
    } elseif (in_array(false, $fields, true)) {
      // some or all fields failed validation
    } else {
      // all fields passed validation
      // use $fields['email'] as the email address
    }
    

    I've used FILTER_UNSAFE_RAW for all fields except email, but perhaps there are better filters that apply.

    0 讨论(0)
提交回复
热议问题