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转义代码,如下所示:
<script>location.href('http://www.runoob.com')</script>
以上代码是安全的,可以正常在页面显示。
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!