在php中的服务器上执行之前对输入进行消毒


Sanitize input before executing at server in php

我想让用户在表单中输入两个变量,Name和Password。我想在输入值中禁用任何XSS或脚本插入。我在表单方法中有以下代码:

<form name="form1" method="post" action="checkpw.php">
Your Name:
<table>
  <tr><td><input class="text" name="name" onBlur="capitalize(this);" maxlength=12 type="text" /></td></tr>
</table> 
Password:
<table>
  <tr><td><input class="text" name="passwd" maxlength=8 type="password" /></td></tr>
  <tr><td align="center"><br/>
     <input class="text" type="submit" name="submitbt" value="Login" />
  </td></tr>
</table>  

以及以下checkpw.php:

<?php
// Clean up the input values 
$post = filter_input_array(INPUT_POST, array(
    'name' => FILTER_SANITIZE_STRING,
    'pw' => FILTER_SANITIZE_STRING,
));
if (is_null($post) || in_array(null, $post)) {
    header("location:login.php");
    return; // missing fields (or failed filter)
} 
// pw is the password sent from the form 
$pw=$_POST['passwd'];
$name=$_POST['name'];
if($pw == 'testpass'){
    header("location:index.php");
} else {
    header("location:wrong.php");
}
?>

这是确保表单发送到服务器并仅在输入值被清除后执行的安全方法吗?

此外,我想将$name值传递给index.php文件。我在index.php中插入如下代码:

<?php echo $name ?>

但它是空的。知道怎么解决吗?

您正在发出header( .. ),这意味着您正在重定向到另一个页面并重新开始。

您有3个选项:

  • 在会话中输入您的$名称
  • 在标头函数中传递$name,如header("location: index.php?name=$name");
  • 不要重定向,而是包括php文件。在这种情况下,您根本不需要会话。也会更快,因为你不需要往返浏览器

至于清理,一开始就可以了。这取决于你以后对数据的处理。我建议,如果把数据放在数据库中更详细地查看该做什么。

magic_quotes_gpc现在应该在大多数服务器上禁用;但是,请阅读本文,了解禁用它们的其他方法。

此外,您可以使用filter_input_array()(PHP>=5.2)来实现此目的:

$post = filter_input_array(INPUT_POST, array(
    'name' => FILTER_SANITIZE_STRING,
    'pw' => FILTER_SANITIZE_STRING,
));
if (is_null($post) || in_array(null, $post)) {
    return; // missing fields (or failed filter)
}
// you can safely use $post['name'] and $post['pw'] here