php基础教程——表单验证(必填、提交后数据保留)
一、表单验证中用到的几个元素记录
1.htmlspecialchars(),用于将用户输入的特殊字符转义为普通字符,比如 < 和 > 之类的 HTML 字符会被替换为 < 和 >
2.$_SERVER["PHP_SELF"] 是一种超全局变量,返回当前页面脚本名字
3.trim()用于删除多余的空格等
4.stripslashes()用于删除用户多输入的反斜线
二、一个简单的表单验证函数
function test_input($str){ $str = trim($str);//去除空格等 $str = stripslashes($str);//去除用户输入的反斜线 $str = htmlspecialchars($str);//转意特殊字符为普通字符 return $str;}
1.php代码中,验证输入框是否为空,是则增加错误信息,用于在HTML中显示,非空则验证和处理输入
2.HTML代码中插入输出错误信息的php代码片段如*
$emailErr为保存错误信息变量,起始为空。
简单示例:
<!DOCTYPE HTML> <html><head><style>.error {color: #FF0000;}</style></head><body> <?php$name = $email = $website = $area = $gender = "";$nameErr = $emailErr = ""; if ($_SERVER['REQUEST_METHOD'] == 'POST'){//attention $_SERVER['REQUEST_METHOD'] if (empty($_POST['name'])){ $nameErr = "姓名必填"; }else{ $name = test_input($_POST['name']); } if (empty($_POST['email'])){ $emailErr = "电邮必填"; }else{ $email = test_input($_POST['email']); } if (empty($_POST['website'])){ $website = ""; }else{ $website = test_input($_POST['website']); } if (empty($_POST['area'])){ $area = ""; }else{ $area = test_input($_POST['area']); } if (empty($_POST['gender'])){ $gender = ""; }else{ $gender = test_input($_POST['gender']); }}function test_input($str){ $str = trim($str);//去除空格等 $str = stripslashes($str);//去除用户输入的反斜线 $str = htmlspecialchars($str);//转意特殊字符为普通字符 return $str;}?><p class="error">*为必填</p><!--attention $_SERVER['PHP_SELF']--><form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">姓名:<input type="text" name="name"><span class="error">*<?php echo $nameErr?></span><br/>电邮:<input type="text" name="email"><span class="error">*<?php echo $emailErr?></span><br/>网址:<input type="text" name="website"><br/>评论:<textarea name="area" rows="4" cols="40"></textarea><br/>性别:<input type="radio" name="gender" value="female">女性<input type="radio" name="gender" value="male">男性<br/><input type="submit" value="提交" name="submit"><br/></form><?phpecho "您的输入是:<br/>";echo "姓名:",$name;echo "<br/>电邮:", $email;echo "<br/>网址:", $website;echo "<br/>评论:", $area;echo "<br/>性别:", $gender;?>
显示裁图:
四、表单数据的保留
在上述代码中只需改动如下 标签中添加PHP片段:
对
对单选,较麻烦,在中添加代码:
<form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">姓名:<input type="text" name="name" value="<?php echo $name;?>"><span class="error">*<?php echo $nameErr?></span><br/>电邮:<input type="text" name="email" value="<?php echo $email;?>"><span class="error">*<?php echo $emailErr?></span><br/>网址:<input type="text" name="website" value="<?php echo $website;?>"><br/>评论:<textarea name="area" rows="4" cols="40"><?php echo $area;?></textarea><br/>性别:<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">女性<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">男性<br/><input type="submit" value="提交" name="submit"><br/></form>