码迷,mamicode.com
首页 > Web开发 > 详细

PHP 表单验证

时间:2018-05-23 11:54:52      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:request   ret   ali   comm   ebs   str   spec   red   htm   

代码:

<html>
<?php
// PHP - 验证Name、E-mail、以及URL

// 定义变量并设置为空值
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
	if (empty($_POST["name"])) {
		$nameErr = "Name is required";
	} else {
		$name = test_input($_POST["name"]);
		// 检查名字是否包含字母和空格
		if (!preg_match("/^[a-z-A-z]*$/", $name)) {
			$nameErr = "Only letters and white space allowed";
		}
	}

	if (empty($_POST["email"])) {
		$emailErr = "Email is requied";
		// 检查电邮语法是否有效
		if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email)) {
			$emailErr = "Invalid email format";
		}
	}

	if (empty($_POST["website"])) {
		$website = "";
	} else {
		$website = test_input($_POST["website"]);
		// 检查URL地址语言是否有效(此正则表达式同样允许URL中的下划线)
		if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $website)) {
			$websiteErr = "Invalid URL";
		}
	}

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

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

function test_input($data) {
	$data = trim($data);
	$data = stripslashes($data);
	$data = htmlspecialchars($data);
	return $data;
}

?>
<head>
	<title>PHP 表单验证</title>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail:
<input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website:
<input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
<label>Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">

</form>
</body>
</html>

  

回显:

技术分享图片

 

存在问题:等深入了解以后再瞅瞅,现在一直看不出哪里出问题了,正则表达式不是很懂,几乎是照本搬科。

 

PHP 表单验证

标签:request   ret   ali   comm   ebs   str   spec   red   htm   

原文地址:https://www.cnblogs.com/xsr7yer/p/9075857.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!