search
HomeBackend DevelopmentPHP TutorialPHP表单之表单验证

一、表单安全

1、htmlspecialchars()函数

把特殊字符转换为 HTML 实体。这意味着 之类的 HTML 字符会被替换为 92d33664ec5f827b86e068a341370a86 。这样可防止攻击者通过在表单中注入 HTML 或 JavaScript 代码(跨站点脚本攻击)对代码进行利用。

跨站点脚本攻击(Cross Site Scripting):为不和层叠样式表(Cascading Style Sheets, CSS)的缩写混淆,故将跨站脚本攻击缩写为XSS。恶意攻击者往Web页面里插入恶意html代码,当用户浏览该页之时,嵌入其中Web里面的html代码会被执行,从而达到恶意攻击用户的特殊目的。

HTML 实体:HTML 中的预留字符必须被替换为字符实体。如果希望正确地显示预留字符,我们必须在 HTML 源代码中使用字符实体(character entities)。

显示结果 描述 实体名称 实体编号
  空格    
小于号 08a4a2ebf1b67a599f6bb509e7e81493 >
& 和号 & &
引号 " "
撇号 ' (IE不支持) '
¢ ¢
£ £ £
¥ 日圆 ¥ ¥
? 欧元
§ 小节 § §
© 版权 © ©
® 注册商标 ® ®
? 商标
× 乘号 × ×
÷ 除号 ÷ ÷

一个简单的加法器(注意看其中的htmlspecialchars

<html><body><form method='post' action='<?php echo htmlspecialchars($_SERVER['PHP_SELF'])?>'><input type="text" pattern="[0-9]*" name="left">+<input type="text" pattern="[0-9]*" name="right">=<input type="submit" value="计算"></form></body></html><?php echo $_POST['left']+$_POST['right']; ?>

2、创建表单验证函数

<html><head><title>表单测试</title></head><body><?php $name = $email = $website=$comment=""; function format_input($data){ $data=trim($data);#去除首尾多余的空白符 $data=stripcslashes($data);#去除用户输入的反斜杠 $data=htmlspecialchars($data);#转化为html实体 return $data; } if($_SERVER['REQUEST_METHOD']=="POST"){ $name=format_input($_POST['name']); $email=format_input($_POST['email']); $website=format_input($_POST['website']); $comment=format_input($_POST['comment']); } ?><form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'])?>">姓名:<input type="text" name="name" /><br /><br />电邮:<input type="text" name="email" /><br /><br />网址:<input type="text" name="website" /><br /><br />评论:<textarea cols="22" rows="5" name="comment"></textarea><br /><br /><input type='submit' value='提交' /></form><?php echo "<br />name:".$name; echo "<br />email:".$email; echo "<br />website:".$website; echo "<br />comment:".$comment; ?></body></html>
二、表单必填 字段 验证规则
Name 必需。必须包含字母和空格。
E-mail 必需。必须包含有效的电子邮件地址(包含 @ 和 .)。
Website 可选。如果选填,则必须包含有效的 URL。
Comment 可选。多行输入字段(文本框)。
<html> <head> <title>表单必填</title> <style> .error {color:#FF0000;} </style> </head> <body> <?php $name = $email = $website=$comment=""; $nameErr=$emailErr=$websiteErr=$commentErr=""; function format_input($data){ $data=trim($data);#去除首尾多余的空白符 $data=stripcslashes($data);#去除用户输入的反斜杠 $data=htmlspecialchars($data);#转化为html实体 return $data; } if($_SERVER['REQUEST_METHOD']=="POST"){ if(empty($_POST['name'])) $nameErr="姓名是必填的!"; else $name=format_input($_POST['name']); if(empty($_POST['email'])) $emailErr="邮箱是必填的!"; else $email=format_input($_POST['email']); $website=format_input($_POST['website']); $comment=format_input($_POST['comment']); } ?> <form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'])?>"> 姓名:<input type="text" name="name" /> <span class="error">*<?php echo $nameErr; ?></span> <br /><br /> 电邮:<input type="text" name="email" /> <span class="error">*<?php echo $emailErr; ?></span> <br /><br /> 网址:<input type="text" name="website" /> <br /><br /> 评论:<textarea cols="22" rows="5" name="comment"></textarea> <br /><br /> <input type='submit' value='提交' /> </form> <?php echo "<br />name:".$name; echo "<br />email:".$email; echo "<br />website:".$website; echo "<br />comment:".$comment; ?> </body> </html>
三、格式匹配

利用正则表达式(Regular Expression)对用户输入的数据进行格式验证。更多有关正则表达式的知识请看正则表达式30分钟入门教程以及正则表达式全部符号解释。

int preg_match ( string $pattern , string $subject );
搜索subject与pattern给定的正则表达式的一个匹配。

Regex quick reference

符号 意义
[abc] A single character: a, b or c
[^abc] Any single character but a, b, or c
[a-z] Any single character in the range a-z
[a-zA-Z] Any single character in the range a-z or A-Z
^ Start of line
$ End of line
\A Start of string
\z End of string
. Any single character
\s Any whitespace character
\S Any non-whitespace character
\d Any digit
\D Any non-digit
\w Any word character (letter, number, underscore)
\W Any non-word character
\b Any word boundary character
(…) Capture everything enclosed
(a b)
a? Zero or one of a
a* Zero or more of a
a+ One or more of a
a{3} Exactly 3 of a
a{3,} 3 or more of a
a{3,6} Between 3 and 6 of a

1、匹配姓名

“/^[a-zA-Z ]*$/”
只允许空格和字母,”^”表示开头,”$”表示结尾,[a-zA-Z ]表示a-z或者A-Z或者空格中的一个字符。

$name = test_input($_POST["name"]);if (!preg_match("/^[a-zA-Z ]*$/",$name)) {  $nameErr = "只允许字母和空格!"; }

2、匹配E-mail

“/([\w-]+\@[\w-]+.[\w-]+)/”
“\w”匹配包括下划线的任何单词字符。等价于’[A-Za-z0-9_]’;
+匹配前面的子表达式一次或多次;
“-“匹配”-“。

3、匹配URL

“/\b(?:(?:https?|ftp):\/\/|www.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i”

四、保留表单中的值

原理:在input标签中嵌入PHP脚本。
如果type=”text”,那么就嵌入value=”
如果type=”radio”,那么就嵌入

最后写了一个简单的登录表单:

<html><head><title>一个简易的登录表单</title></head><body><?php $email = $passwd =""; $emailErr=$passwdErr=""; if($_SERVER['REQUEST_METHOD']=='POST'){ if(empty($_POST['email'])) $emailErr='请输入邮箱!'; else if(preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$_POST['email'])) $email=clear_input($_POST['email']); else $emailErr="请输入有效的邮箱!"; if(empty($_POST['passwd'])) $passwdErr='请输入密码!'; else $passwd=clear_input($_POST['passwd']); } function clear_input($data){ $data=trim($data); $data=stripcslashes($data); $data=htmlspecialchars($data); return $data; } ?><form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">邮箱:<input type="text" name="email" value="<?php echo $email;?>" /><span class='error'><?php echo $emailErr;?></span><br />密码:<input type="password" name="passwd" value="<?php echo $passwd;?>"/><span class='error'><?php echo $passwdErr;?></span><br /><input type="submit" name="submit" value="登录"></form><?php echo "你输入的<br />"; echo "邮箱:".$email; echo "<br />"; echo "密码:".$passwd; ?></body></html>

版权声明:本文为Lshare原创文章,需要转载的请联系我,有问题欢迎评论或私信。

Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools