Home  >  Article  >  Backend Development  >  trim, stripslashes, htmlspecialchars functions

trim, stripslashes, htmlspecialchars functions

巴扎黑
巴扎黑Original
2016-11-12 09:29:542009browse


通过 PHP 验证表单数据

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

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

3f1c4e4b6b16bbbd69b2ee476dc4f83alocation.href('http://www.hacked.com')2cacc6d41bbb37262a98f745aa00fbf0

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

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

现在这条代码显示在页面上或 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;
}
?>


Statement:
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
Previous article:Form required fieldsNext article:Form required fields