欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php如何实现表单数据验证

程序员文章站 2022-04-02 18:07:42
...
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);

输出结果:

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"

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

示例:

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

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

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

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

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

<script>location.href('http://www.runoob.com')</script>

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

&lt;script&gt;location.href('http://www.runoob.com')&lt;/script&gt;

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

以上就是php如何实现表单数据验证的详细内容,更多请关注其它相关文章!