PHP - 验证表单

时间:2017-12-15 15:47:33

标签: php

我试图为表单创建一个简单的验证脚本,但无法让它正常工作。我只被重定向到错误页面...

如下所示,只允许使用小写和大写字母作为名字和姓氏,仅限电子邮件的电子邮件结构,仅限电话号码,空格和(+)。如果不允许用户输入,则用户将被重定向到简单的错误页面。

$first_name = $last_name = $email = $mobile = $country = "";

if (isset($_SERVER["REQUEST_METHOD"] == "POST")) {

    // Only small and capitalized letters allowed
    $first_name = test_input($_POST['first_name']);
    if(!preg_match("/^[a-zA-Z ]*$/",$first_name)) { 
        die("Error! Non allowed signs were used in 'first name'");
    }

    // Only small and capitalized letters allowed
    $last_name = test_input($_POST['last_name']);
    if(!preg_match("/^[a-zA-Z ]*$/",$last_name)) { 
        die("Error! Non allowed signs were used in 'last name'");
    }

    // Only email allowed
    $email = test_input($_POST['email']);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        die ("Error! Non allowed signs were used in 'email'");
    }

    // Only numbers, space and + allowed
    $mobile = test_input($_POST['mobile']);
    if(!preg_match("/^[0-9 +-]+$/",$mobile)) { 
        die ("Error! Non allowed signs were used in 'mobile'");
    }

    // Country input (no validation)
    $country = $_POST['country'];

    }

    // Function test input
    function test_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }

HTML基本上是这样的:

<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 

    <input type="text" required="" name="first_name" style="width:100%" />

    [And so on...]

</form>

1 个答案:

答案 0 :(得分:2)

-b

不正确〜if (isset($_SERVER["REQUEST_METHOD"] == "POST")) {` 返回一个布尔值,有效地使isset或类似

尝试:

if(false=='POST')