首页 > 解决方案 > PHP脚本不断发送空白电子邮件

问题描述

由于某种原因,当满足空置条件时,php 脚本不会结束,并且当用户按下提交按钮时会继续发送空白电子邮件。即使显示错误消息,我也会在收件箱中收到一封空白电子邮件。请帮忙。

<?php
$name_error=$email_error=$message_error=$send_error="";
$name=$email=$message=$success="";

if(isset($_POST['submit'])){  

        //check name
  if(empty($_POST['name'])){
    $name_error= 'Enter name<br />';  
  } else {
    $name=$_POST['name'];
    if(!preg_match('/^[a-zA-Z\s]+$/', $name)){
      $name_error= 'Letters and spaces only';      
    }         
  }
       //check email
  if(empty($_POST['email'])){
    $email_error='Enter email<br />';    
  } else {
    $email=$_POST['email'];
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
      $email_error='Enter a valid email';          
    }
  }
        //check message
  if(empty($_POST['message'])){
    $message_error= 'Enter message<br />';   
  } else {
    $message=test_input($_POST['message']);
  }
  
  if($name=='' or $email=='' or $message==''){
    $send_error='The message could not be sent.'; 
  }
  
    $to="contact@contact.com";
    $subject="Contact from website";
    $txt="From: ".$name.".\n\n".$message;
    $body="From: ".$email; 

  if(mail($to, $subject, $txt, $body)){
    $success='Message sent';
    $name=$email=$message=$success=""; 
  } else {
    $send_error='The message could not be sent.';        
  }

}

function test_input($data){
  $data=trim($data);
  $data=stripslashes($data);
  $data=htmlspecialchars($data);
  return $data;
}

?>
```

标签: phpvalidationemail

解决方案


根据您的代码-无论如何它都会发送电子邮件。我相信你的意思应该“停止”脚本的延续的条件是:

  if($name=='' or $email=='' or $message==''){
    $send_error='The message could not be sent.'; 
  }

脚本将继续执行以下几行,而不是条件返回 true 或 false。其余代码 - 是发送电子邮件的代码。

    $to="contact@contact.com";
    $subject="Contact from website";
    $txt="From: ".$name.".\n\n".$message;
    $body="From: ".$email; 

  if(mail($to, $subject, $txt, $body)){
    $success='Message sent';
    $name=$email=$message=$success=""; 
  } else {
    $send_error='The message could not be sent.';        
  }

解决方案是else用于验证条件。

  if($name=='' or $email=='' or $message==''){
    $send_error='The message could not be sent.'; 
  } else {
    $to="contact@contact.com";
    $subject="Contact from website";
    $txt="From: ".$name.".\n\n".$message;
    $body="From: ".$email; 

    if(mail($to, $subject, $txt, $body)){
      $success='Message sent';
      $name=$email=$message=$success=""; 
    } else {
      $send_error='The message could not be sent.';        
    } 

  }

推荐阅读