停止空表单提交 PHP


Stopping empty form submission PHP

我一直在尝试实现服务器验证以防止我的联系我们页面中的空白电子邮件,但我不确定如何在 PHP 中执行此操作,这是我的代码:

<?php
$field_name = $_POST['cf_name'];
$field_email = $_POST['cf_email'];
$field_tel = $_POST['cf_tel'];
$field_message = $_POST['cf_message'];

$mail_to = 'test@test.com, test@test.com, test@test.com';
$subject = 'Just iStuff Mobile Contact Us: '.$field_name;
$body_message = 'From: '.$field_name."'n";
$body_message .= 'E-mail: '.$field_email."'n";
$body_message .= 'Telephone Number: '.$field_tel."'n";
$body_message .= 'Message: '.$field_message;
$headers = 'From: '.$field_email."'r'n";
$headers .= 'Reply-To: '.$field_email."'r'n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) { ?>
    <script language="javascript" type="text/javascript">
        alert('Thank you for your email, we have received your message and will reply within the next few days.');
        window.location = 'contactus.html';
    </script>
<?php
}
else { ?>
    <script language="javascript" type="text/javascript">
        alert('Message failed, please try again or email test@test.com');
        window.location = 'contactus.html';
    </script>
<?php
}
?>

谁能帮我做到这一点,在线教程没有涵盖这种方式......

谢谢

在 $mail_to 之前。

您可以先在服务器端验证_POST/_GET。

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

或者,您可以先在客户端进行验证。它将节省您的时间和资源。

只需测试变量的"空"并提前退出。像这样:

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

您可能希望对几乎所有输入字段执行此操作。

此外,您可以使用JavaScript(jQuery有一些不错的插件)来防止用户首先提交无效数据。这不会消除在服务器端执行此操作的需要(因为他们可以禁用 JS,或者恶意人员可能会故意绕过此措施),但它可以使其成为更加用户友好的体验。

您可以使用过滤器; 由于您将传递的电子邮件地址用作mail()操作的一部分,因此最好还验证:

$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
}

我已经对除电子邮件以外的所有字段都使用了FILTER_UNSAFE_RAW,但也许有更好的过滤器适用。

尝试在

表单中放入提交输入<input type="submit" name="sub" value="Submited">当它被点击时。

<?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');
  }
  .....