php基础教程——表单验证(必填、提交后数据保存)

WBOY
Release: 2016-06-13 12:13:49
Original
1252 people have browsed it

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;}
Copy after login
三、表单中必填项的提示代码

      1.php代码中,验证输入框是否为空,是则增加错误信息,用于在HTML中显示,非空则验证和处理输入

      2.HTML代码中插入输出错误信息的php代码片段如*

$emailErr为保存错误信息变量,起始为空。

简单示例:

 <style>.error {color: #FF0000;}</style> <?php $name = $email = $website = $area = $gender = "";$nameErr = $emailErr = ""; if ($_SERVER[&#39;REQUEST_METHOD&#39;] == &#39;POST&#39;){//attention $_SERVER[&#39;REQUEST_METHOD&#39;]	if (empty($_POST[&#39;name&#39;])){		$nameErr = "姓名必填";	}else{		$name = test_input($_POST[&#39;name&#39;]);	}	if (empty($_POST[&#39;email&#39;])){		$emailErr = "电邮必填";	}else{		$email = test_input($_POST[&#39;email&#39;]);	}	if (empty($_POST[&#39;website&#39;])){		$website = "";	}else{		$website = test_input($_POST[&#39;website&#39;]);	}	if (empty($_POST[&#39;area&#39;])){		$area = "";	}else{		$area = test_input($_POST[&#39;area&#39;]);	}	if (empty($_POST[&#39;gender&#39;])){		$gender = "";	}else{		$gender = test_input($_POST[&#39;gender&#39;]);	}}function test_input($str){	$str = trim($str);//去除空格等	$str = stripslashes($str);//去除用户输入的反斜线	$str = htmlspecialchars($str);//转意特殊字符为普通字符	return $str;}?><p class="error">*为必填</p><!--attention $_SERVER[&#39;PHP_SELF&#39;]-->
Copy after login
姓名:*
电邮:*
网址:
评论:
性别:女性男性

";echo "姓名:",$name;echo "
电邮:", $email;echo "
网址:", $website;echo "
评论:", $area;echo "
性别:", $gender;?>

显示裁图:


四、表单数据的保留

在上述代码中只需改动如下 标签中添加PHP片段:

之间

对单选,较麻烦,在中添加代码:

Copy after login
姓名:*
电邮:*
网址:
评论:
性别: value="female">女性 value="male">男性




Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template