I'm usingPHP, HTML, SMTP server and PHPmailerto create a contact us form with user input validation. But after pressing "Submit" button it gives me an error:
Invalid address: (Sender): Fatal error: Uncaught PHPMailer\PHPMailer\Exception: Invalid address: (from): in C:\xampp\htdocs\RESPONSIVE SITE3_2\Supplier\phpmailer\phpmailer\src\PHPMailer.php:1324 Stack trace: #0 C:\xampp\htdocs\RESPONSIVE SITE3_2\send-email.php(74): PHPMailer\PHPMailer\PHPMailer->setFrom('', '') #1 {main} throws in C:\xampp\htdocs\RESPONSIVE SITE3_2\vendor\phpmailer\phpmailer\src\PHPMailer.php line 1324
PHP code:
SMTPDebug = SMTP::DEBUG_SERVER; $mail->isSMTP(); $mail->SMTPAuth = true; $mail->Host = "smtp.gmail.com"; $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $mail->Port = 587; require_once 'config.php'; $mail->Username = SMTP_USERNAME; $mail->Password = SMTP_PASSWORD; $mail->setFrom($email, $name); $mail->addAddress("myemail@gmail.com", "Ads"); $mail->Subject = $subject; $mail->Body = "Name: $name\nEmail: $email\n\n$message"; $mail->send(); header("Location: sent.html"); ?>
HTML code
I tried different tutorials - without success. I need this form
I am very new to this, please explain it in very simple language :)
diagnosis
If either validation
if
statement is true, a string variable$emailErr
will be set.Then the code exits the
if
block again and the script continues on its merry way and attempts to send the email. There is no logic in the code to prevent this.Finally,
$emailErr
is never used because the code redirects the user to another HTML page that cannot involve that variable.solution
If any validation fails, you need some additional logic to tell the code to skip the email sending part. A very simple way to do this cleverly is to use a "flag" variable.
For example:
PS BTW, your regex is too restrictive - seeWhat characters are allowed in email addresses?. Since you're already using
FILTER_VALIDATE_EMAIL
, you don't need it under any circumstances.