如何在PHP中验证我的联系表单?我的代码的解决方案

时间:2019-02-07 10:04:13

标签: php forms validation

我的网站上有一个联系表,其中包含必填的电子邮件字段。 我正在尝试验证PHP中的输入字段,以避免用户提交空的电子邮件字段。我尝试了一些教程,但到目前为止没有成功。如果这里有人可以帮助我修复下面的代码,我将不胜感激

<?php
$recipient_email    = "info@example.com"; //recepient
$from_email         = "info@example.com";

if($_POST){

    $subject = 'Example.com';
    $from = "info@example.com";
    $to = "recipient@your-server.com";
    $name   = filter_var($_POST["name"], FILTER_SANITIZE_STRING); 
    $street = filter_var($_POST["strasse"], FILTER_SANITIZE_STRING); 
    $tel    = filter_var($_POST["tel"], FILTER_SANITIZE_STRING);
    $email  = filter_var($_POST["email"], FILTER_VALIDATE_EMAIL);
    $name   = filter_var($_POST["name"], FILTER_SANITIZE_STRING); 
    $street = filter_var($_POST["strasse"], FILTER_SANITIZE_STRING); 
    $email  = filter_var($_POST["email"], FILTER_SANITIZE_STRING); 
    $tel    = filter_var($_POST["tel"], FILTER_SANITIZE_STRING); 

    $message_body =  "Message from $name\n";
    $message_body .=  "------------------------------\n";

    $message_body .=  "Name: $name\n";
    $message_body .=  "Street: $street \n";
    $message_body .=  "Email: $email \n";
    $message_body .=  "Telefon: $tel \n";

    $headers = "MIME-Version: 1.0\r\n"; 
    $headers .= "From:".$from_email."\r\n"; 
    $headers .= "Reply-To: ".$email."\r\n";
    $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n"; 

    //message text
    $body = "--$boundary\r\n";
    $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
    $body .= "Content-Transfer-Encoding: base64\r\n\r\n"; 
    $body .= chunk_split(base64_encode($message_body)); 
    exit;
}

$headers = "From:".$from_email."\r\n".  
            "Reply-To: ".$email. "\r\n" .
            "X-Mailer: PHP/" . phpversion();
$body = $message_body;
}

$sentMail = mail($recipient_email, $subject, $body, $headers);
if($sentMail) //output success or failure messages
{       
    header("Location: http://www.example.com");
}else{
    print 'Could not send mail! Please check your PHP mail configuration.';  
    exit;
}
}
?>

1 个答案:

答案 0 :(得分:0)

由于您已经在检查变量,因此只需简单地确定是否退出代码即可。在您的filter_vars之后执行以下操作:

... start of your code

    $name   = filter_var($_POST["name"], FILTER_SANITIZE_STRING); 
    $street = filter_var($_POST["strasse"], FILTER_SANITIZE_STRING); 
    $tel    = filter_var($_POST["tel"], FILTER_SANITIZE_STRING);
    $email  = filter_var($_POST["email"], FILTER_VALIDATE_EMAIL);
    $name   = filter_var($_POST["name"], FILTER_SANITIZE_STRING); 
    $street = filter_var($_POST["strasse"], FILTER_SANITIZE_STRING); 
    $email  = filter_var($_POST["email"], FILTER_SANITIZE_STRING); 
    $tel    = filter_var($_POST["tel"], FILTER_SANITIZE_STRING); 

if(!$email) {
  print 'Your email is wrong.';
  exit;
}

... continue with your code