您的位置:首页 > 编程语言 > PHP开发

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

2015-12-07 15:02 639 查看
<!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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: