Table of Contents
1、htmlspecialchars()函数
2、创建表单验证函数
1、匹配姓名
2、匹配E-mail
3、匹配URL
Home Backend Development PHP Tutorial PHP表单之表单验证

PHP表单之表单验证

Jun 23, 2016 pm 01:30 PM

一、表单安全

1、htmlspecialchars()函数

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

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

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

显示结果 描述 实体名称 实体编号
  空格    
小于号 < <
> 大于号 > >
& 和号 & &
引号 " "
撇号 ' (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']; ?>
Copy after login

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>
Copy after login
二、表单必填 字段 验证规则
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>
Copy after login
三、格式匹配

利用正则表达式(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 = "只允许字母和空格!"; }
Copy after login

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>
Copy after login

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

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

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

PHP Logging: Best Practices for PHP Log Analysis PHP Logging: Best Practices for PHP Log Analysis Mar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

See all articles