我已经在互联网上搜索了多个小时。我的Phpmailer运作良好,但即使表单有误,它也会发送电子邮件,例如接收电子邮件。我不知道表格是否有错误。我是否还需要在Phpmailer文件中查询数据库,还是可以使用PHP注册查询中已经完成的查询返回?
在我的注册PHP查询中,我检查是否接收了电子邮件。如果电子邮件被接收,则表单显示错误,但是PHPmailer即使电子邮件被接收到错误也发送电子邮件。如何停止PHPmailer表单发送带有表单错误的电子邮件。 请注意,我的变量$ user保留检查是否收到了电子邮件。如何使PHPmailer也使用变量$ user?
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
if(array_key_exists("first",$_POST) && $_POST["first"] != "" && array_key_exists("last",$_POST) && $_POST["last"] != "" && (array_key_exists('email', $_POST) and PHPMailer::validateAddress($_POST['email'])) && array_key_exists("unit",$_POST) && $_POST["unit"] != "") {
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'gator*****hostgator.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '***********.com'; // SMTP username
$mail->Password = '*********'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
//Recipients
$mail->setFrom('admin********.com', 'Admin');
$mail->addAddress('admin*****.com', 'HP Website'); // Add a recipient
$mail->addAddress($_POST['email']); // Name is optional
// $mail->addReplyTo($email);
// $mail->addCC($_REQUEST['email']);
// $mail->addBCC('bcc@example.com');
//Attachments
// $mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$unit = $_POST['unit'];
$bed = $_REQUEST['bed'];
$bath = $_REQUEST['bath'];
$web = $_REQUEST['web'];
$phone = $_REQUEST['phone'];
$manage = $_REQUEST['manage'];
//$unit = $_REQUEST['unit'];
//$uid = $_REQUEST['uid'];
$ck = $_REQUEST['rent'];
//Content
$mail->addEmbeddedImage('img/logo4.png', 'logo');
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Your HP unit is signed up';
// $first_name = $_POST['first_name'];
// $last_name = $_POST['last_name'];
// $license_type = $_POST['license_type'];
$mail->Body = '<p style="background-color:#333; color:orange; text-align:center; font-weight:bolder">Welcome to the HP Owner website</p>
<p style="text-align:center; margin:0"><img src="cid:logo"></p>
<p><strong>Name: </strong>'.$first.' '.$last.'</p>
<p><strong>Email: </strong>'.$email.'</p>
<p><strong>Unit#: </strong>'.$unit.'</p>
<p><strong>Bed: </strong>'.$bed.'</p>
<p><strong>Bath: </strong>'.$bath.'</p>
<p><strong>Website: </strong>'.$web.'</p>
<p><strong>Phone: </strong>'.$phone.'</p>
<p><strong>Management: </strong>'.$manage.'</p>
<p><strong>Show on HP website - (1 means show): </strong>'.$ck.'</p>
<p>If any of your info above is wrong, login with your username and password. Click on Update My Unit button and update your info..<br>
<br>If you checked the box Show On Rental Site, your unit will show - refresh the rental site or go to http://www.*********.php<br>
<br>If you need to delete everything and start over - contact the admin email admin***********.com';
$mail->AltBody = 'HP Owner Web Site - You are signed up';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
}
?>
和我的PHP查询
require_once 'dbh.inc.php';
//include_once 'mailer0.php';
include_once 'includes/mailer.php';
// Init vars
$first = $last = $email = $unit = $bed = $bath = $web = $phone = $manage = $pwd = $confirm_password = $ck = '';
$name_err = $unit_err = $bed_err = $bath_err = $phone_err = $email_err = $password_err = $confirm_password_err = '';
// Process form when post submit
if($_SERVER['REQUEST_METHOD'] === 'POST'){
// Sanitize POST
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
// Put post vars in regular vars
$first = trim($_POST['first']);
$last = trim($_POST['last']);
$email = trim($_POST['email']);
$unit = trim($_POST['unit']);
$bed = trim($_POST['bed']);
$bath = trim($_POST['bath']);
$web = trim($_POST['web']);
$phone = trim($_POST['phone']);
$manage = trim($_POST['manage']);
// $uid = trim($_POST['uid']);
$pwd = trim($_POST['pwd']);
$confirm_password = trim($_POST['confirm_password']);
$ck = trim($_POST['rent']);
// Validate email
if(empty($email)){
$email_err = 'Please enter email';
} else {
$stmt = $pdo->prepare("SELECT * FROM condos_hp WHERE user_email=?");
if($stmt->execute([$email]));{
$user = $stmt->fetch();
}
if ($user) {
// email found
$email_err = 'Email is already taken';
}
unset($stmt);
}
// Validate name
if(empty($first) || empty($last)){
$name_err = 'Please enter name';
}
// Validate name
if(empty($unit)){
$unit_err = 'Please enter your unit #';
}
// Validate name
if(empty($bed) || empty($bath)){
$bed_err = 'Please enter bed/bath #';
}
// Validate name
if(empty($phone)){
$phone_err = 'Please enter your phone';
}
// Validate password
if(empty($pwd)){
$password_err = 'Please enter password';
} elseif(strlen($pwd) < 6){
$password_err = 'Password must be at least 6 characters ';
}
// Validate Confirm password
if(empty($confirm_password)){
$confirm_password_err = 'Please confirm password';
} else {
if($pwd !== $confirm_password){
$confirm_password_err = 'Passwords do not match';
}
}
// Make sure errors are empty
if(empty($name_err) && empty($email_err) && empty($password_err) && empty($confirm_password_err)){
// Hash password
$pwd = password_hash($pwd, PASSWORD_DEFAULT);
// Prepare insert query
// (user_firstname, user_lastname, user_email, user_unit, user_bed, user_bath, user_web, user_phone, user_manage, rent)
$sql = 'INSERT INTO condos_hp (user_firstname, user_lastname, user_email, user_unit, user_bed, user_bath, user_web, user_phone, user_manage, user_pwd, rent) VALUES (:first, :last, :email, :unit, :bed, :bath, :web, :phone, :manage, :pwd, :rent)';
// $sql = 'INSERT INTO condos_hp (name, email, password) VALUES (:name, :email, :password)';
if($stmt = $pdo->prepare($sql)){
// Bind params
// $stmt->bindParam(':name', $name, PDO::PARAM_STR);
// $stmt->bindParam(':email', $email, PDO::PARAM_STR);
// $stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':first', $first, PDO::PARAM_STR);
$stmt->bindParam(':last', $last, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':unit', $unit, PDO::PARAM_STR);
$stmt->bindParam(':bed', $bed, PDO::PARAM_STR);
$stmt->bindParam(':bath', $bath, PDO::PARAM_STR);
$stmt->bindParam(':web', $web, PDO::PARAM_STR);
$stmt->bindParam(':phone', $phone, PDO::PARAM_STR);
$stmt->bindParam(':manage', $manage, PDO::PARAM_STR);
// $stmt->bindParam(':uid', $uid, PDO::PARAM_STR);
$stmt->bindParam(':pwd', $pwd, PDO::PARAM_STR);
$stmt->bindParam(':rent', $ck, PDO::PARAM_STR);
// $stmt->bindParam(':id', $id);
// Attempt to execute
if($stmt->execute()){
// Redirect to login
header('Location: login0.php');
} else {
die('Something is not right');
}
}
unset($stmt);
}
// Close connection
unset($pdo);
}
?>
更新的当前代码.......
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Include db config
require_once 'dbh.inc.php';
//include_once 'mailer0.php';
// Init vars
$first = $last = $email = $unit = $bed = $bath = $web = $phone = $manage = $uid = $pwd = $confirm_password = $ck = '';
//$name_err = $unit_err = $bed_err = $bath_err = $phone_err = $email_err = $uid_err = $password_err = $confirm_password_err = '';
//$error = isset($_SESSION['error']) ? $_SESSION['error'] : [];
// Process form when post submit
if (isset($_POST["register"])) {
// $error = array()
//($_SERVER['REQUEST_METHOD'] === 'POST'){
// echo var_dump($_POST);
// echo '<br/>';
// print_r($_POST);
//$error = ($_SESSION['error']);
// Sanitize POST
// $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$error = array();
var_dump($error);
if (!empty($error)) {
echo "not empty";
} else {
echo "empty";
}
// Put post vars in regular vars
$first = trim($_POST['first']);
$last = trim($_POST['last']);
$email = trim($_POST['email']);
$unit = trim($_POST['unit']);
$bed = trim($_POST['bed']);
$bath = trim($_POST['bath']);
$web = trim($_POST['web']);
$phone = trim($_POST['phone']);
$manage = trim($_POST['manage']);
$uid = trim($_POST['uid']);
$pwd = trim($_POST['pwd']);
$confirm_password = trim($_POST['confirm_password']);
$ck = ($_POST['rent']);
// Validate email
if (empty($email)) {
$error['email'] = "Please enter email";
} else {
// check if email is taken
/*$sql = 'SELECT * FROM condos_hp WHERE user_email = :email';
if($stmt = $pdo->prepare($sql)){
// Bind variables
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
// Attempt to execute
if($stmt->execute()){
// Check if email exists
$user = $stmt->fetch()
if ($user){
$email_err = 'Email is already taken';
}
} else {
die('Something went wrong');
}
}*/
/*$sql= "SELECT * FROM condos_hp WHERE uid = :uid";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':uid', $uid);
//$stmt = $pdo->prepare("SELECT uid FROM condos_hp WHERE uid=:uid");
//$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->execute();
//$user = $stmt->fetchALL(PDO::FETCH_ASSOC);
//print_r($stmt->fetchObject())
//$stmt->setFetchMode(PDO::FETCH_ASSOC);
$user = $stmt->fetch();
if ($user) {
// email found
$uid_err = 'UserID is already taken';
echo var_dump($user);*/
$stmt = $pdo->prepare("SELECT uid FROM condos_hp WHERE uid=?");
$stmt->bindValue('1', $uid);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) {
// $error[] = 'sorry username already taken !';
// email found
$error['uid'] = "user ID already taken";
// die;
// header('Location: register.php');
print_r($user);
// print_r($error);
//} else { // or not die('Something went wrong'); }
} else {
// echo 'user does not exist<br>';
}
unset($stmt);
}
// Validate name
if (empty($first) || empty($last)) {
$error['name'] = "Enter name";
}
// Validate name
if (empty($unit)) {
$error['unit'] = 'Please enter your unit #';
}
// Validate name
if (empty($bed) || empty($bath)) {
$error['rooms'] = 'Please enter bed/bath #';
}
// Validate name
if (empty($phone)) {
$error['phone'] = 'Please enter your phone';
}
//Check phone # format 000-000-0000
if (!preg_match("/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i", $phone)) {
$error['phone'] = 'Please enter correct phone format';
}
//Check manage format
if (!preg_match("/^(\s\(([^)]+)\))?[[:punct:]]?\p{Lu}+(?:[\s'-]?[\p{L}\d]+)+(\(([^)]+)\))*$/", $manage)) {
$error['manage'] = 'Please enter correct management format';
}
//Check password format 4 and 8 digits long and include at least one numeric digit.
// if (!preg_match("/^(?=.*\d).{4,8}$/", $pwd)) {
// $password_err = 'Password must be at least 4 digits with 1 number ';
if (empty($uid)) {
$error['uid'] = 'Please enter uid';
}
// Validate password
if (empty($pwd)) {
$error['pwd'] = 'Please enter password';
}
if (!preg_match("/^(?=.*\d).{4,8}$/", $pwd)) {
$error['pwd'] = 'Password must be at least 4 digits with 1 number ';
}
// Validate Confirm password
if (empty($confirm_password)) {
$error['pwdpar'] = 'Please confirm password';
} else {
if ($pwd !== $confirm_password) {
$error['pwdpar'] = 'Passwords do not match';
}
}
// Make sure errors are empty
if (empty($error)) {
// Hash password
$pwd = password_hash($pwd, PASSWORD_DEFAULT);
// Prepare insert query
// (user_firstname, user_lastname, user_email, user_unit, user_bed, user_bath, user_web, user_phone, user_manage, rent)
$sql = 'INSERT INTO condos_hp (user_firstname, user_lastname, user_email, user_unit, user_bed, user_bath, user_web, user_phone, user_manage, uid, user_pwd, rent) VALUES (:first, :last, :email, :unit, :bed, :bath, :web, :phone, :manage, :uid, :pwd, :rent)';
// $sql = 'INSERT INTO condos_hp (name, email, password) VALUES (:name, :email, :password)';
if ($stmt = $pdo->prepare($sql)) {
// Bind params
// $stmt->bindParam(':name', $name, PDO::PARAM_STR);
// $stmt->bindParam(':email', $email, PDO::PARAM_STR);
// $stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':first', $first, PDO::PARAM_STR);
$stmt->bindParam(':last', $last, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':unit', $unit, PDO::PARAM_STR);
$stmt->bindParam(':bed', $bed, PDO::PARAM_STR);
$stmt->bindParam(':bath', $bath, PDO::PARAM_STR);
$stmt->bindParam(':web', $web, PDO::PARAM_STR);
$stmt->bindParam(':phone', $phone, PDO::PARAM_STR);
$stmt->bindParam(':manage', $manage, PDO::PARAM_STR);
$stmt->bindParam(':uid', $uid, PDO::PARAM_STR);
$stmt->bindParam(':pwd', $pwd, PDO::PARAM_STR);
$stmt->bindParam(':rent', $ck, PDO::PARAM_STR);
// $stmt->bindParam(':id', $id);
// Attempt to execute
if ($stmt->execute()) {
// Redirect to login
header('Location: register.php');
} else {
die('Something is not right');
}
}
unset($stmt);
}
// Close connection
unset($pdo);
}
//include_once 'includes/mailer.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"
integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="includes/style.css">
<title>Register HP Account</title>
<script>
function validate(form) {
fail = validateFirst(form.first.value)
fail += validateLast(form.last.value)
fail += validateEmail(form.email.value)
fail += validateUnit(form.unit.value)
fail += validateBed(form.bed.value)
fail += validateBath(form.bath.value)
fail += validateWebsite(form.web.value)
fail += validatePhone(form.phone.value)
fail += validateManage(form.manage.value)
fail += validateUid(form.uid.value)
fail += validatePassword(form.pwd.value)
if (fail == "") return true
else {
alert(fail);
return false
}
}
</script>
<script src="includes/validate_functions.js"></script>
</head>
<body>
<div class="container">
<div class="col-md-8 mx-auto">
<h2 style="text-align:center">HP Sign-Up Form</h2>
<p style="text-align:center">Fill in this form to register</p>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST">
<div class="form-row justify-content-center">
<div class="form-group col-md-4">
<label for="first">First Name</label>
<input type="text" name="first"
class="form-control form-control-lg <?php echo (!empty($error['name'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($first); ?>">
<span class="invalid-feedback"><?php echo $error['name']; ?></span>
</div>
<div class="form-group col-md-4">
<label for="last">Last Name</label>
<input type="text" name="last"
class="form-control form-control-lg <?php echo (!empty($error['name'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($last); ?>">
<span class="invalid-feedback"><?php echo $error['name']; ?></span>
</div>
</div>
<div class="form-row justify-content-center">
<div class="form-group col-md-6">
<label for="email">Email Address</label>
<input type="email" name="email"
class="form-control form-control-lg <?php echo (!empty($error['email'])) ? 'is-invalid' : ''; ?>"
value="<?php echo $email; ?>">
<span class="invalid-feedback"><?php echo $error['email']; ?></span>
</div>
<div class="form-group col-md-2">
<label for="unit">Unit #</label>
<input type="text" name="unit"
class="form-control form-control-lg <?php echo (!empty($error['unit'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($unit); ?>">
<span class="invalid-feedback"><?php echo $error['unit']; ?></span>
</div>
</div>
<div class="form-row justify-content-center">
<div class="form-group col-md-1">
<label for="bed">Bed</label>
<input type="text" name="bed"
class="form-control form-control-lg <?php echo (!empty($error['rooms'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($bed); ?>">
<span class="invalid-feedback"><?php echo $error['rooms']; ?></span>
</div>
<div class="form-group col-md-1">
<label for="bath">Bath</label>
<input type="text" name="bath"
class="form-control form-control-lg <?php echo (!empty($error['rooms'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($bath); ?>">
<span class="invalid-feedback"><?php echo $error['rooms']; ?></span>
</div>
<div class="form-group col-md-6">
<label for="web">Website</label>
<input type="text" name="web" class="form-control form-control-lg"
value="<?php echo htmlentities($web); ?>">
</div>
</div>
<div class="form-row justify-content-center">
<div class="form-group col-md-3">
<label for="phone">Phone - 000-000-0000</label>
<input type="text" id="yourphone2" name="phone" placeholder="123-456-7890"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
class="form-control form-control-lg <?php echo (!empty($error['phone'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($phone); ?>">
<span class="invalid-feedback"><?php echo $error['phone']; ?></span>
</div>
<div class="form-group col-md-5">
<label for="manage">Management - (VRBO, SELF, etc.)</label>
<input type="text" name="manage"
class="form-control form-control-lg <?php echo (!empty($error['manage'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($manage); ?>">
<span class="invalid-feedback"><?php echo $error['manage'] = 'Please management'; ?></span>
</div>
</div>
<div class="form-row justify-content-center">
<div class="form-group col-md-2">
<label for="uid">UserID - 8 length</label>
<input type="text" name="uid"
class="form-control form-control-lg <?php echo (!empty($error['uid'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($uid); ?>" placeholder="6 chars ex.betty12">
<span class="invalid-feedback"><?php echo $error['uid']; ?></span>
</div>
<div class="form-group col-md-3">
<label for="pwd">Password - min 6 digits</label>
<input type="password" name="pwd"
class="form-control form-control-lg <?php echo (!empty($error['pwd'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($pwd); ?>"
placeholder="6 to 8 digits include 1 num - ex.1234, absd12">
<span class="invalid-feedback"><?php echo $error['pwd']; ?></span>
</div>
<div class="form-group col-md-3">
<label for="confirm_password">Confirm Password</label>
<input type="password" name="confirm_password"
class="form-control form-control-lg <?php echo (!empty($error['pwdpar'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($confirm_password); ?>">
<span class="invalid-feedback"><?php echo $error['pwdpar']; ?></span>
</div>
</div>
<div class="form-row justify-content-center">
<div class="custom-control custom-checkbox">
<input type="hidden" name="rent" value="0">
<input type="checkbox" value="1" name="rent" class="custom-control-input" id="customCheck1"
checked="checked">
<label class="custom-control-label" for="customCheck1">Check to show on the rental site</label>
</div>
</div>
<div class="form-row justify-content-center">
<div class="form-group col-md-4">
<input type="submit" value="register" name="register" class="btn btn-success btn-block">
</div>
<div class="form-group col-md-4">
<a href="login0.php" class="btn btn-light btn-block">Have an account? Login</a>
</div>
</div>
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"
integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T"
crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="dist/jquery-input-mask-phone-number.js"></script>
<script>
//xxx-xxx-xxxx format code
$(document).ready(function () {
$('#yourphone2').usPhoneFormat({
format: 'xxx-xxx-xxxx',
});
});
</script>
<?php require_once './includes/footer.php'; ?>
</html>