trim、stripslashes、htmlspecialchars函数

经过 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

<?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;  
}  
?>
相关文章
相关标签/搜索