PHP联系表单失败

时间:2017-02-07 23:42:13

标签: php html css forms contact

我想知道这个联系表格中出了什么问题。我不确定原因,但它经常默认为else并说Something went wrong, please try again later.我无法弄清楚原因,而且error_log没有显示任何内容。有什么明显我错过了吗?我是PHP的新手。

PHP

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $message = $_POST['message'];
    $captcha = $_POST['captcha'];
    $from = 'From: HankSmith.com Contact Form'; 
    $to = 'thatbraxjohnsonguy@gmail.com'; 
    $subject = 'HANK SMITH CONTACT FORM';

    $body = "
            From: $name\n 
            E-Mail: $email\n 
            Phone: $phone\n
            Message: $message\n";

    if ($_POST['submit'] and $captcha == 4) {                
        if (mail ($to, $subject, $body, $from)) { 
        echo '<p style="margin-top: 150; text-align:center; font-size: 18px;">Your message has been sent! Click <a href="../index.php">here</a> to return to the website.</p>';
    } else { 
        echo '<p>Something went wrong, try again later!</p>'; 
    }
}
?>

HTML表单

            <form class="contactform" method="post" action="php/contact.php">
                <h3>Name</h3>
                <input class="form inputboxes" type="text" name="name">
                <h3>Email</h3>
                <input class="form inputboxes" type="text" name="email">
                <h3>Phone</h3>
                <input class="form inputboxes" type="text" name="phone">
                <h3>Message</h3>
                <textarea class="form inputboxes" name="message"></textarea>
                <h3 class="captchastyle">Are you real? What is 2 + 2?</h3><input class="captcha captchastyle" type="text" name="captcha" maxlength="1">
                <input class="form submit" name="submit" type="submit" value="Submit">
            </form>

2 个答案:

答案 0 :(得分:1)

根据您的情况使用isset

if (isset($_POST['submit']) && $captcha == 4)

检查字段是否为空并且表单已提交。

此处&&and更好,请在此处查看原因:https://stackoverflow.com/a/11861068

答案 1 :(得分:1)

当我将其复制到我的文本编辑器中时,它抛出了一个解析错误,因为if(mail)...部分中的echo语句没有右括号。我从不使用'和',我通常使用'&amp;&amp;',但在这种情况下它似乎并不重要。

if ($_POST['submit'] && $captcha == 4) {                
        if (mail ($to, $subject, $body, $from)) { 
        echo '<p style="margin-top: 150; text-align:center; font-size: 18px;">Your message has been sent! Click <a href="../index.php">here</a> to return to the website.</p>';
        } // THIS MUST BE HERE
    } else { 
        echo '<p>Something went wrong, try again later!</p>'; 
    }

另外,你可能想要if(mail)...语句的'else'条件。如果你看到一个空白页面,那将是因为你没有处理如果mail()函数返回false会发生什么:

if (mail ($to, $subject, $body, $from)) { 
  echo '<p style="margin-top: 150; text-align:center; font-size: 18px;">Your message has been sent! Click <a href="../index.php">here</a> to return to the website.</p>';
} else {
  echo '<p>Problem sending mail!';
}

老实说,本机PHP mail()函数很糟糕!请考虑改为使用SwiftMailerPHPMailer

相关问题