php对输入的安全性处理函数trim、stripslashes、htmlspecialchars

PHP 验证表单数据,通过 PHP 的 htmlspecialchars() 函数传递所有变量。
在我们使用 htmlspecialchars() 函数后,如果用户试图在文本字段中提交以下内容:

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

- 代码不会执行,因为会被保存为转义代码,就像这样:

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

现在这条代码显示在页面上或 e-mail 中是安全的。
在用户提交该表单时,我们还要做两件事:
(通过 PHP trim() 函数)去除用户输入数据中不必要的字符(多余的空格、制表符、换行)
(通过 PHP stripslashes() 函数)删除用户输入数据中的反斜杠(\)
接下来我们创建一个检查函数提高效率,命名为 check_input()。
现在,我们能够通过 check_input() 函数检查每个 $_POST 变量:
实例

<?php
// 定义变量并设置为空值
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

滚动至顶部