【问题标题】:Do I have to purify the submit form data when creating mysqli connection based on user input?根据用户输入创建mysqli连接时是否必须净化提交表单数据?
【发布时间】:2014-04-14 20:04:43
【问题描述】:

我正在尝试为我的客户编写一个 php 安装程序来安装我的 php 程序。我的意思是,我的客户端可以运行 domain.com/myscript/install/index.php,输入数据库名称、密码主机名等,一旦提交表单,我的安装程序脚本将连接到 mySQL 数据库(基于用户的输入),然后创建一些表等。

即。

$mysqli = new mysqli($_POST['hostname'],$_POST['username'],$_POST['password'],$_POST['port']);

那么,我想知道在这种情况下,是否有必要对 $_POST 进行净化?

【问题讨论】:

  • 是的!这对一个人来说是一种良好的卫生习惯,你不知道它会如何被利用,所以不要假设。
  • 净化用户输入的数据总是一个好主意,即使您认为只有受信任的用户才会使用它。
  • 我想知道我应该使用哪个php函数,因为此时我无法使用mysqli_real_escape_string

标签: php mysql security mysqli


【解决方案1】:

无论如何,始终清理用户输入。此时您不需要mysqli_real_escape_string,该函数仅转义某些字符以安全插入表中。绝对不是你现在需要的。使用PHP's built-in filter functions

<?php

$sanitize_string = array(
  'filter' => FILTER_SANITIZE_STRING,
  'flags'  => FILTER_REQUIRE_SCALAR | FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH,
);

$user_input = filter_input_array(
  INPUT_POST,
  'hostname' => $sanitize_string, // You could also use the IP one, check for persistent, ...
  'username' => $sanitize_string,
  'password' => FILTER_UNSAFE_RAW, // It's going to be hashed, who cares!
  'port'     => array(
     'filter' => FILTER_VALIDATE_INT,
     'flags'  => FILTER_REQUIRE_SCALAR,
     'options' => array('min_range' => 666, 'max_range' => 3600),
   ),
   true
);

foreach ($user_input as $input) {
  if (!$input) { // Either NULL or FALSE, we don't care!
    trigger_error("No no my dear!", E_USER_ERROR);
  }
}

list($host, $user, $pass, $port) = $user_input;
$mysqli = new \mysqli($host, $user, $pass, $port);

?>

【讨论】:

  • 我必须调用 filter_var 吗?
  • 可以对每个变量使用filter_var(),如上图直接使用`filter_input_array()函数。
【解决方案2】:

由于您正在处理 SQL,因此您不会按照传统意义上的方式进行操作。相反,您需要确保它符合 MySQL 接口选项。换句话说,发布“127.0.0.1;从用户中删除”不会造成问题,但也不会创建有效的连接。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 2011-09-27
    • 2015-08-14
    相关资源
    最近更新 更多