-->

Form to Email PHP Validation fallback using PHPMai

2020-08-04 10:03发布

问题:

i have a basic contact form on a website. i need to send the form results to 2 email addresses... 1) me, & 2) a confirmation to the person who submitted the form. the form results sent to the submitter has a different message in it.

i plan to add jQuery validation & Ajax but first i want to get the PHP to work. so i don't think i need a lot of PHP validation, just a basic - if critical fields are empty, then error message, as a fallback.

i'm using PHPMailer but unfortunately their documentation is sorely lacking for someone of my lack-of-php skills. but after much google'ing, i've been able to piece together something that mostly works. here is my code utilizing a small form (more fields to come later).

this DOES send the form to both email addresses - great!

the part i'm having trouble with is the validation & error/success messages.

if i just use the return $mail->send(); at the end of the function sendemail section, it sends fine. but if i try to submit the form without anything in the fields, nothing happens. so i tried adding this if(!$mail->send()) {...else...} piece i found somewhere, and it also works with valid form info, but not if empty.

so, what should i use instead of this? or would it be something different to the end if/else part?

<?php

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

    date_default_timezone_set('US/Central');

    require 'PHPMailer-5.2.26/PHPMailerAutoload.php';

    function sendemail(
            $SK_emailTo, 
            $SK_emailSubject, 
            $SK_emailBody
            ) {

        $mail = new PHPMailer;

        $mail->setFrom('myEmail@gmail.com', 'My Name');

        $mail->addReplyTo($_POST['email'], $_POST['name']);

        $mail->addAddress($SK_emailTo);
        $mail->Subject  = $SK_emailSubject;
        $mail->Body     = $SK_emailBody;
        $mail->isHTML(true);

        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com';
        $mail->SMTPAuth = true;
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;
        $mail->Username = 'myEmail@gmail.com';
        $mail->Password = 'myPwd';


        //return $mail->send(); //this works by itself, without IF/ELSE, but doesn't return error if empty form fields
        if(!$mail->send()) {
            return 'There is a problem' . $mail->ErrorInfo;
        }else{
            return 'ok'; // this works but i don't know why
        }

    } //end function sendemail

    // form fields to variables
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    // from function sendmail to ASSIGN VALUES to...
    /*      $SK_emailTo, 
            SK_emailSubject, 
            $SK_emailBody */
    if (sendemail(
            'myEmail@address.com', 
            'First email subject', 
            'Form results to me...
             <br><br>'.$message
        )) {

        sendemail(
            $email, 
            'Second email subject', 
            'Confirmation email to person who submitted the form... 
             <br><br>'.$message
        );

        $msg = 'Email sent!';
    } else {
        $msg = 'Email failed!' . $mail->ErrorInfo;
    }

} //end if submit
?>

as a sidenote, why does the return 'ok'; work? what does the 'ok' part attach to?

thanks!


//////////////////////// EDIT: NEW INFO BUT STILL NOT SOLVED ////////////////////////

based on the suggestions & edits by Mauro below (and in that posts comments), here is where i'm at now...

<?php
if (isset($_POST['submit'])) {

    date_default_timezone_set('US/Central');

    require 'PHPMailer-5.2.26/PHPMailerAutoload.php';

    function sendemail(
            $SK_emailTo, 
            $SK_emailSubject, 
            $SK_emailBody
            ) {

        $mail = new PHPMailer(true);

        $mail->setFrom('myEmail@gmail.com', 'My Name');

        $mail->addReplyTo($_POST['email'], $_POST['name']);

        $mail->addAddress($SK_emailTo);
        $mail->Subject  = $SK_emailSubject;
        $mail->Body     = $SK_emailBody;
        $mail->isHTML(true);

        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com';
        $mail->SMTPAuth = true;
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;
        $mail->Username = 'myEmail@gmail.com';
        $mail->Password = 'myPwd';

        return $mail->send();

    } //end function sendemail

    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    try {
        sendemail(
            'myEmail@address.com', 
            'First email subject', 
            'Form results to me...
             <br><br>'.$message
        );
        sendemail(
            $email, 
            'Second email subject', 
            'Confirmation email to person who submitted the form... 
             <br><br>'.$message
        );
        echo 'Email sent!';
    } //end try

    catch (phpmailerException $e) { //catches PHPMailer errors
        echo 'There is a problem; the message did NOT send. Please go back and check that you have filled in all the required fields and there are no typos in your email address.';
        echo $e->errorMessage();
    } 
    catch (Exception $e) { //catches validation errors
        echo 'There is a problem; the message did NOT send. Please either go back and try again or contact us at email@address.com';
        echo $e->getMessage();
    }

    function validateEmpty($string, $name = 'name') {
        $string = trim($string);
        if ($string == '') {
            throw new Exception(sprintf('%s is empty.', $name));
        }
    }

} //end if submit
?>

STILL...

1) Mauro suggested i log the error message using use error_log(). how do i do that? is that what produces the text file of error messages in the ftp directory?

2) Mauro also suggested using an $error & $success flag. what is that & how do i do it?

3) i want to have the custom error message in the above catch if the "name" &/or "email" fields (& possibly others) are simply empty. Mauro wrote the function validateEmpty code above, but i can't get it to work. do i have it in the wrong placement within the script or doing something else wrong with it?

3b) it looks to me like this function is just for the "name" field, do i have to duplicate it for the "email" field?

PLEASE REMEMBER... i want to be able to have a SIMPLE validation here as a fallback in case Javascript/Jquery isn't working for some reason. also note that the above DOES "send" the email correctly; so am now just trying to get the validation & error message to work right.

thank you for your time & expertise!

回答1:

tl;dr: both statements evaluate to true. It's better to return true or false instead of strings and handle the message later.

First I'll take care of your question, then I'll make some suggestions on good practices.

When you use return x; in PHP and most languages, you're "sending" x back to where you called the function. So, when your code is executed it will be read as:

if('ok')

or

if ('Error info...')

PHP evaluates the condition on an if statement (this is the part between parenthesis) as true or false by converting it to the boolean type. The string to boolean conversion in PHP is basically as follows: any non-empty string evaluates as TRUE (follow the link, check first table, last column).

So, your function is returning 'ok' if it succeeds, 'Error info...' if it fails, these are both non-empty strings and thereof evaluated as true, so no matter if the first email sending attempt went well, your script will try to send the second one, and will always set $msg to 'Email sent!'.

Here's some advice on how to fix your script so it works (and looks) better:

  1. As @Matt suggested it's always best to validate the data by yourself instead of relying on PHPMailer to do so. Despite PHPMailer will return an error if the destination address is invalid, it's a good practice not to even call the library if the email is not valid. So:

    • First, validate the data using javascript, so your user get's instant feedback.
    • Then, validate it using PHP (maybe create a new validate() function that may use filter_var() to validate emails.
    • Last, send the email only if the previous two were successful.
  2. To follow your chain of thought, you should be evaluating if the string returned by sendemail() equals to 'ok' or not:

    if (sendemail(...) == 'ok')
    

    But, instead of evaluating two different strings ('ok' or 'Error info...') it's better if the function returned boolean values instead, and since PHPMailer's send() already does, just keep it as you have it commented:

    return $mail->send()
    
  3. Your last line is using $mail, a variable that you declared inside a function and you never made global, so it won't be available at that point and since you're trying to get a property (ErrorInfo) you'll be firing two PHP notices: Undefined variable and Trying to get a property from a non-object. You COULD just add global $mail at the top of the function and that will make it globally available (outside your function's scope) but this is considered a bad practice since in large pieces of code you might get confused.

    Instead, a neater way of firing the error would be to throw/catch an exception:

    function sendemail(...) {
    
        // ... PHPMailer config ...
    
        if ($mail->send()) {
            return true;
        } else {
            throw Exception('Error: ' + $mail->ErrorInfo);
        }
    }
    
    // later...
    try {
        sendemail()
        $msg = 'Email sent!';
    } catch (Exception $e) {
        $msg = 'Email failed!' . $e->getMessage();
    }
    

    Here, if there's a problem with the emails sending, your function will throw a generic exception and the catch part will be executed.

    EVEN BETTER

    If you initialize PHPMailer like this:

    $mail = new PHPMailer(true); // note the parameter set to true.
    

    It will throw an exception by itself if it fails to send the email and you'll be able to catch the exception:

    function sendemail(...) {
        $mail = PHPMailer(true); // this line
        // ... PHPMailer config ...
        return $mail->send(); // just to return something, we aren't really using this value anymore.
    }
    
    // later...
    try {
        sendemail(...)
        $msg = 'Email sent!';
    } catch (phpmailerException $e) {
        echo $e->errorMessage(); // Catch PHPMailer exceptions (email sending failure)
    } catch (Exception $e) {
        echo $e->getMessage(); // Boring error messages from anything else!
    }
    

Never forget to read the docs!



标签: php phpmailer