php错误处理异常

I found the following codes for processing a contact form and would like to add error handling and exceptions to them.

HTML Form looks like:

<div class="contact-form">
    <form id="contact-form" action="sendmail.php" method="post" title="Contact Form" role="form">
        <div class="col-sm-6">
            <div class="form-group">
                <label for="contact-name">Name</label>
                <input type="text" name="name" placeholder="Enter your name..." class="contact-name" id="contact-name">
            </div>
            <div class="form-group">
                <label for="contact-email">Email</label>
                <input type="text" name="email" placeholder="Enter your email..." class="contact-email" id="contact-email">
            </div>
            <div class="form-group">
                <label for="contact-subject bold">Subject</label>
                <input type="text" name="subject" placeholder="Your subject..." class="contact-subject" id="contact-subject">
            </div>
        </div>
        <div class="col-sm-6">
            <div class="form-group">
                <label for="contact-message">Message</label>
                <textarea name="message" placeholder="Your message..." class="contact-message" id="contact-message"></textarea>
            </div>
        </div>
        <div class="col-sm-12 text-center">
            <button type="submit" class="btn btn-default sketchFlowPrint" id="submit">Send</button>
        </div>
    </form>
</div>

sendmail.php looks like:

<?php

// Email address verification
function isEmail($email) {
    return(preg_match("/^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
}

if($_POST) {

    // Enter the email where you want to receive the message
    $emailTo = 'example@gmail.com';

    $clientName = addslashes(trim($_POST['name']));
    $clientEmail = addslashes(trim($_POST['email']));
    $subject = addslashes(trim($_POST['subject']));
    $message = addslashes(trim($_POST['message']));

    $array = array();
    $array['nameMessage'] = '';
    $array['emailMessage'] = '';
    $array['messageMessage'] = '';

    if($clientName == '') {
        $array['nameMessage'] = 'Please enter your name.';
    }
    if(!isEmail($clientEmail)) {
        $array['emailMessage'] = 'Please insert a valid email address.';
    }
    if($message == '') {
        $array['messageMessage'] = 'Please enter your message.';
    }
    if($clientName != '' && isEmail($clientEmail) && $message != '') {
        // Send email
    $headers = "From: " . $clientName . " <" . $clientEmail . ">" . "
" . "Reply-To: " . $clientEmail . "
";
    mail($emailTo, $subject . ' (Example - Website)', $message, $headers);
    }

    echo json_encode($array);

}   else {
        header ('location: index.html#contact');
}

?>

jquery script looks like:

// Contact form
$('.contact-form form').submit(function(e) {
    e.preventDefault();

    var form = $(this);
    var nameLabel = form.find('label[for="contact-name"]');
    var emailLabel = form.find('label[for="contact-email"]');
    var messageLabel = form.find('label[for="contact-message"]');

    nameLabel.html('Name');
    emailLabel.html('Email');
    messageLabel.html('Message');

    var postdata = form.serialize();

    $.ajax({
        type: 'POST',
        url: 'sendmail.php',
        data: postdata,
        dataType: 'json',
        success: function(json) {
            if(json.nameMessage !== '') {
                nameLabel.append(' - <span class="red error-label"> ' + json.nameMessage + '</span>');
            }
            if(json.emailMessage !== '') {
                emailLabel.append(' - <span class="red error-label"> ' + json.emailMessage + '</span>');
            }
            if(json.messageMessage !== '') {
                messageLabel.append(' - <span class="red error-label"> ' + json.messageMessage + '</span>');
            }
            if(json.nameMessage === '' && json.emailMessage === '' && json.messageMessage === '') {
                form.fadeOut('fast', function() {
                    form.parent('.contact-form').append('<h2 class="text-center"><span class="orange">Thanks for contacting us!</span> We will get back to you very soon.</h2>');
                });
            } 
        }
    });
});

The code works very nice excepts for TWO things:

  1. I receive the email but the clients email address is not displayed anywhere on my email and I cannot reply to the client, I tried messing around with the headers section but couldn't get it right (please help me fix this).
  2. I want the form to let the user know if the form was not submitted. For this I added this code to the jquery script after the last "if" function:

    else { form.fadeOut('fast', function() { form.parent('.contact-form').append('Something went wrong! Please refresh page and try again.'); }); }.

I would like to add exceptions to this. I want this "else" function I added to only execute if there is something wrong with the anything else except for when the user did not fill all the required fields (if the user did not fill in the required fields the form must display "Please enter you name." or "Please insert a valid email address." or "Please enter your message." on top of the input fields depending on which field was not filled). Hope this makes sense.

in your php, you should define another couple of variables

1. $my_email = "info@example.com"; //senders email
2. $subject = "Query from My Domain"; //a  subject line

and then use

mail($_REQUEST['email'],$subject,$message,$headers,"-f{$my_email}");

where

 $headers = "From: " . $my_email;

actually i usually use

$headers = "From: " . $my_email;
$headers .= PHP_EOL;
$headers .= "MIME-Version: 1.0".PHP_EOL;
$headers .= "Content-Type: multipart/mixed;".PHP_EOL;
$headers .= " boundary=\"boundary_sdfsfsdfs345345sfsgs\"";

i don't quite why you have the receiver's email in the php; these values should be posted from your form

e.g. $field_order_keys = array('name','email','comment');

and then requested using $_REQUEST

this will fix the sender's email problem

i have created a plunker of a generic form of my contact php script that i generally use. It has gibberish and field-checking etc in it. Perhaps you will find it useful (the link doesn't land on it, it's the contactconfirm.php above it)