php基础–页面传值,输入验证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<!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>

原文链接: http://blog.csdn.net/zhz459880251/article/details/50205837