Stopping empty form submission PHP

前端 未结 4 1308
一整个雨季
一整个雨季 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: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.

提交回复
热议问题