PHP联系表单未验证

时间:2019-05-10 11:41:27

标签: php contact-form

我在使用PHP联系人表格时遇到问题。发送表单时我没有遇到任何错误,但是验证不起作用。任何帮助,将不胜感激。 在此先感谢

这是我的导入方式

<form action="<?= $_SERVER['PHP_SELF']; ?>" method="POST ">

这是PHP代码

<?php
//Define Variables and Set to Default
$name_error = $email_error = $phone_error = $message_error = "";
$name = $product = $email = $phone = $message = "";

//Form is Submitted with POST Method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"])) {
        $name_error = "Name is Required";
    } else {
        $name = test_input($_POST["name"]);
        //check if name only contains letter and whitespaces
        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
            $name_error = "Only Letters and Whitespaces allowed";
        }
    }

    if (empty($_POST["email"])) {
        $email_error = "E-Mail is Required";
    } else {
        $email = test_input($_POST["email"]);
        //check if email is well formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $email_error = "Invalid Email";
        }
    }

    if (empty($_POST["phone"])) {
        $phone_error = "Mobile Number is Required";
    } else {
        $phone = test_input($_POST["phone"]);
        //check if email is well formed
        if (!preg_match("/^(\d[\s-]?)?)[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone)) {
            $phone_error = "Invalid Phone Number";
        }
    }

    if (empty($_POST[message])) {
        $message = "";
    } else {
        $message = test_input($_POST["message"]);
    }
}

function test_input($data){
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>

0 个答案:

没有答案