PHP表单

2018-11-12  本文已影响0人  有木
<?php
// 如果是有POST请求才执行这些
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // 存储每个字段的错误信息
    $nameErr = $emailErr = $genderErr = $websiteErr = "";
    // 存储每个字段的信息
    $name = $email = $gender = $comment = $website = "";
    // 对每个字段进行判断
    if (empty($_POST["name"])) {
        $nameErr = "Name is required";
    } else {
        $name = test_input($_POST["name"]);
    }

    if (empty($_POST["email"])) {
        $emailErr = "Email is required";
    } else {
        $email = test_input($_POST["email"]);
    }

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

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

    if (empty($_POST["gender"])) {
        $genderErr = "Gender is required";
    } else {
        $gender = test_input($_POST["gender"]);
    }
}

// 用来把要输出到页面上的东西全部变成直接输出的,没有意义的
function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>
<html>
    <head>
        <style>
        .error{
            color:red;
        }
        </style>
    </head>
    <body>
        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
            Name:<input type="text" name="name"><span class="error">* <?php echo $nameErr;?></span><br>
            E-mail:<input type="text" name="email"><span class="error">* <?php echo $emailErr;?></span><br>
            Website:<input type="text" name="website"><span class="error"><?php echo $websiteErr;?></span><br>
            Comment:<textarea name="comment" rows="5" cols="40"></textarea><br>
            Gender:
                <input type="radio" name="gender" value="female">Famale
                <input type="radio" name="gender" value="male">Male<span class="error">* <?php echo $genderErr;?></span><br>
            <input type="submit">
        </form>
        <h1>Your Input:</h1>
        <?php
            echo test_input($name);
            echo test_input($email);
            echo test_input($website);
            echo test_input($comment);
            echo test_input($gender);
        ?>
    </body>
</html>
上一篇下一篇

猜你喜欢

热点阅读