php错误处理异常

时间:2016-06-27 14:09:53

标签: javascript php jquery ajax html5

我找到了以下用于处理联系表单的代码,并希望为它们添加错误处理和异常。

HTML表单如下所示:

<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看起来像:

<?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 . ">" . "\r\n" . "Reply-To: " . $clientEmail . "\r\n";
    mail($emailTo, $subject . ' (Example - Website)', $message, $headers);
    }

    echo json_encode($array);

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

?>

jquery脚本看起来像:

// 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>');
                });
            } 
        }
    });
});

对于 TWO 的事情,代码的效果非常好:

  1. 我收到了电子邮件,但客户的电子邮件地址没有显示在我的电子邮件的任何地方,我无法回复客户端,我尝试搞乱标题部分,但无法正确处理(请帮我修复此问题) )。
  2. 我希望表单让用户知道表单是否未提交。为此,我在最后一个&#34; if&#34;之后将此代码添加到jquery脚本中。功能:

    其他{     form.fadeOut(&#39; fast&#39;,function(){         form.parent(&#39; .contact-form&#39;)。追加(&#39;出了点问题!请刷新页面再试一次。&#39;);     });     }。

  3. 我想为此添加例外。我想要这个&#34;否则&#34;功能我添加只执行如果其他任何东西有问题,除非用户没有填写所有必填字段(如果用户没有填写表格必须显示的必填字段&#34;请输入你的名字。&#34;或&#34;请插入有效的电子邮件地址。&#34;或&#34;请输入您的信息。&#34;在输入字段的顶部,具体取决于未填写的字段。希望这是有道理的。

1 个答案:

答案 0 :(得分:0)

在你的php中,你应该定义另外几个变量

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

然后使用

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

,其中

 $headers = "From: " . $my_email;
实际上我通常使用

$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\"";

我不知道为什么你在php中收到了接收者的电子邮件;这些值应该从您的表单中发布

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

然后使用$_REQUEST

请求

这将修复发件人的电子邮件问题

我创建了一个plunker我通常使用的联系人php脚本的通用形式。它有乱码和现场检查等。也许你会发现它很有用(链接不会落在它上面,它就是它上面的contactconfirm.php)