PHP基础--页面传值,输入验证

<!DOCTYPE html>
<html>
<body>


<?php $name = $email = $gender = $comment = $website = ""; $nameErr = $emailErr = $genderErr = $websiteErr = ""; if ($_SERVER['REQUEST_METHOD'] == "POST") { if(empty($_POST['name'])) { $nameErr = "请输入姓名"; } else { $name = test_input($_POST['name']); if (!preg_match("/^[a-zA-Z]*$/", $name)) { $nameErr = "只允许输入字母"; } echo $name; } if(empty($_POST['mail'])) { $emailErr = "请输入邮件"; } else { $email = test_input($_POST['mail']); echo $email; } if(empty($_POST['website'])) { $websiteErr = ""; } else { $website = test_input($_POST['website']); echo $website; } if(empty($_POST['comment'])) { $comment = ""; }else { $comment = test_input($_POST['comment']); echo $comment; } if (empty($_POST["gender"])) { $genderErr = "请选择性别"; } else { $gender = test_input($_POST["gender"]); echo $gender; } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?>


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

    姓名:
    <input type="text" name="name" style="height: 15px" value="<?php echo $name?>">
    <span class="error" style="color: crimson">* <?php echo $nameErr;?></span>
    <br><br>
    邮件:
    <input type="text" name="mail" value="<?php echo $email ?>">
    <span class="error" style="color: crimson">* <?php echo $emailErr;?></span>
    <br><br>
    网址:
    <input type="text" name="website" value="<?php echo $website ?>">
    <span class="error"><?php echo $websiteErr;?></span>
    <br><br>
    年龄:
    <input type="radio" name="gender" value="female" <?php if (isset($gender) && $gender=="female") echo "checked";?>><input type="radio" name="gender" value="male" <?php if (isset($gender) && $gender=="male") echo "checked" ?>><span class="error" style="color: crimson">* <?php echo $genderErr;?></span>
    <br><br>
    评论:
    <textarea name="comment" rows="5" cols="40"></textarea>
    <br><br>
    <input type="submit" value="提交">
</form>



</body>
</html>

你可能感兴趣的:(PHP基础--页面传值,输入验证)