通过 PHP 验证表单数据

我们要做的第一件事是通过 PHP 的 htmlspecialchars() 函数传递所有变量。

在我们使用 htmlspecialchars() 函数后,如果用户试图在文本字段中提交以下内容:

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

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

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

现在这条代码显示在页面上或 e-mail 中是安全的。

在用户提交该表单时,我们还要做两件事:

(通过 PHP trim() 函数)去除用户输入数据中不必要的字符(多余的空格、制表符、换行)

(通过 PHP stripslashes() 函数)删除用户输入数据中的反斜杠(\)

接下来我们创建一个检查函数(相比一遍遍地写代码,这样效率更好)。

我们把函数命名为 test_input()。

现在,我们能够通过 test_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;
}
?>
登录后复制


09-16 04:18