我正在尝试建立一个使用ajax和PHP发送邮件的联系表单。 ajax,并且电子邮件提交工作正常,但是PHP验证不起作用,并且我在服务器的电子邮件框中收到了未经过滤的用户凭据,这是代码,请帮助php验证不起作用,并且用户在表单中输入的任何数据未过滤并按原样发送。
<?php
session_start();
include_once('includes/db_connect.php');
if(isset($_POST['name']) && $_POST['name'] && isset($_POST['phone']) && $_POST['phone'] && isset($_POST['email']) && $_POST['email'] && isset($_POST['message']) && $_POST['message']){
$name = mysqli_real_escape_string($con, $_POST['name']);
$phone = mysqli_real_escape_string($con, $_POST['phone']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$message = mysqli_real_escape_string($con, $_POST['message']);
if(( !preg_match ("/^[a-zA-Z\s]+$/",$name))||(strlen($name) < 3)){
echo json_encode(array('success' => 'invalid name'));
}else{
$name_error = "";
}
if((!is_numeric($phone))||(strlen($phone) !=12)){
echo json_encode(array('success' => 'invalid phone'));
}else{
$phone_error = "";
}
if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
echo json_encode(array('success' => 'invalid email'));
}else{
$email_error = "";
}
if(strlen($message)<10){
echo json_encode(array('success' => 'invalid message'));
}else{
$message_error = "";
}
if(empty($name_error) && empty($phone_error) && empty($email_error)&& empty($message_error)){
error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED ^ E_STRICT);
ini_set("include_path", '/home/extensiv/php:' . ini_get("include_path") );
require_once "Mail.php";
$host = "ssl://mail.mywebsite.com";
$username = "support@mywebsite.com";
$password = "mypassword";
$port = "465";
$to = "support@mywebsite.com";
$email_from = $email;
$email_subject = "Is it working?: " ;
$email_body = $message.$phone ;
$email_address = "support@mywebsite.com";
$headers = array ('From' => $email_from, 'To' => $to, 'Subject' => $email_subject, 'Reply-To' => $email_address);
$smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));
$mail = $smtp->send($to, $headers, $email_body);
if (PEAR::isError($mail)) {
echo json_encode(array('success' => 'submit error'));
} else {
echo json_encode(array('success' => 'submit success'));
}
}else{
echo json_encode(array('success' => 'invalid credentials'));
}
}else{
echo json_encode(array('success'=>'No data received'));
}
?>
答案 0 :(得分:0)
您永远不会将$ name_error,$ phone_error,$ email_error或$ message_error设置为任何值。 您的条件将始终为true,因为$ name_error(和其他条件)都将为null。当为null时,Empty返回true。
要解决此问题,请将$ name_error(及其他)设置为错误字符串,然后从字符串中回显它。
if(( !preg_match ("/^[a-zA-Z\s]+$/",$name))||(strlen($name) < 3)){
$name_error = json_encode(array('success' => 'invalid name'));
echo $name_error;
}else{
$name_error = "";
}
我还建议您在第一个错误之后添加一个die()。否则,您可能最终得到包含多个json对象的返回有效载荷。