表单提交时的非法性有效性验证

文件32-3.php代码:

<form method="post" action="32-4.php">
	Name:<input type="text" name="username" value="" />
	<br />
	<input type="submit" value="Submit it!"/>

</form>

文件32-4.php代码:

<?php
//使用isset()验证变量是否存在,是否非法提交
//注意:此处说的非法提交是指没有经过表单提交,没有生成全局变量,而不是username字段为空
//empty()判断变量是否为空(判断有无输入,且0也作为非法值)
if(isset($_POST['username'])){
	echo "username it exist!";		//注意一个问题:空字符串也是数据(即不输入数据),也可以赋值给$_POST['username']
	echo $_POST['username'];
}else{
	echo "username is not exist!";
}
echo '<br />';
?>

问题:在表单输入带html标签的文本,提交后会将html解析

eg.
1.输入<b>Hello!<b/>;点击submit
2.跳转到指定页面输出为加粗的Hello!字符

<?php
//解决办法:在输出username之前对其处理 htmlspecialchars()
//其他常规判断:
//trim(),前后空格过滤
//strlen(),字符串长度判断,限制
//is_numeric(),是否为纯数字
//正则表达式验证格式是否合法,eg.邮箱地址

if(isset($_POST['username'])){
	echo "username it exist!";		
	$username = htmlspecialchars($_POST['username']);
	$username = trim($username);
	if(strlen($username)<=2){
		echo "the username it too short!<br />";
		exit;
	}
        echo $username;
}else{
	echo "username is not exist!";
}
echo '<br />';

?>

 

你可能感兴趣的:(php表单提交,非法性验证,有效性验证)