Home > Backend Development > PHP Problem > How to implement form data validation in php

How to implement form data validation in php

Guanhui
Release: 2023-02-28 22:36:02
Original
3248 people have browsed it

How to implement form data validation in php

php如何实现表单数据验证

首先通过“trim()”函数去除用户输入数据中不必要的字符 (如:空格,tab,换行);

示例:

$text   = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello  = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = trim($text);
var_dump($trimmed);

$trimmed = trim($text, " \t.");
var_dump($trimmed);

$trimmed = trim($hello, "Hdle");
var_dump($trimmed);

// 清除 $binary 首位的 ASCII 控制字符
// (包括 0-31)
$clean = trim($binary, "\x00..\x1F");
var_dump($clean);
Copy after login

输出结果:

string(32) "        These are a few words :) ...  "
string(16) "    Example string
"
string(11) "Hello World"

string(28) "These are a few words :) ..."
string(24) "These are a few words :)"
string(5) "o Wor"
string(14) "Example string"
Copy after login

然后使用“stripslashes()”函数去除用户输入数据中的反斜杠;

示例:

$str = "Is your name O\'reilly?";

// 输出: Is your name O'reilly?
echo stripslashes($str);
Copy after login

最后在调用“htmlspecialchars()”函数将HTML代码进行转义。

我们对用户所有提交的数据都通过 PHP 的 htmlspecialchars() 函数处理。

当我们使用 htmlspecialchars() 函数时,在用户尝试提交以下文本域:

<script>location.href(&#39;http://www.runoob.com&#39;)</script>
Copy after login

该代码将不会被执行,因为它会被保存为HTML转义代码,如下所示:

&lt;script&gt;location.href(&#39;http://www.runoob.com&#39;)&lt;/script&gt;
Copy after login

以上代码是安全的,可以正常在页面显示。

The above is the detailed content of How to implement form data validation in php. For more information, please follow other related articles on the PHP Chinese website!

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