使用 PHP 验证表单数据

来源:互联网 发布:网络通端口映射工具 编辑:程序博客网 时间:2024/05/01 16:28

当用户提交表单时,我们将做以下两件事情,:

  1. 使用 PHP trim() 函数去除用户输入数据中不必要的字符 (如:空格,tab,换行)。
  2. 使用PHP stripslashes()函数去除用户输入数据中的反斜杠 (\)      

我们将这些过滤的函数写在一个我们自己定义的函数中,这样可以大大提高代码的复用性。

将函数命名为 test_input()。


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


现在,我们可以通过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;
}
?>

运行实例 »

注意我们在执行以上脚本时,会通过$_SERVER["REQUEST_METHOD"]来检测表单是否被提交 。如果 REQUEST_METHOD 是 POST, 表单将被提交 - 数据将被验证。如果表单未提交将跳过验证并显示空白。

在以上实例中使用输入项都是可选的,即使用户不输入任何数据也可以正常显示。

在接下来的章节中我们将介绍如何对用户输入的数据进行验证。


0 0
原创粉丝点击