php - 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;
}
?>
```
解决方案
根据您的代码-无论如何它都会发送电子邮件。我相信你的意思应该“停止”脚本的延续的条件是:
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.';
}
}
推荐阅读
- angular - this.router.navigate 没有检测到 safari 的任何变化
- javascript - 如何使用 jquery 创建一组选定选项?
- sql - 在oracle sql中拆分字符串时面临问题
- android - 无法从静态方法 Flutter 访问实例成员
- c++ - 卤化物函数构造函数
- ansible - 使用 Ansible Molecule 进行测试时如何跳过一些角色任务?
- java - “getText”语法不起作用并且显示错误
- c++ - 相同的方程和相同的参数为什么返回不同的计算结果?
- python - 是否有一个函数可以从 python 列表的 m 个元素中获取 n 个元素?
- c++ - opencv c++ 加载图像,得到非常大的像素值