php 终极清洁/安全功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4223980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:20:10  来源:igfitidea点击:

The ultimate clean/secure function

phpsecurityxsssql-injection

提问by Karem

I have a lot of user inputs from $_GETand $_POST... At the moment I always write mysql_real_escape_string($_GET['var'])..

我有很多来自$_GET和的用户输入$_POST......目前我总是写mysql_real_escape_string($_GET['var'])......

I would like to know whether you could make a function that secures, escapes and cleans the $_GET/$_POSTarrays right away, so you won't have to deal with it each time you are working with user inputs and such.

我想知道您是否可以创建一个立即保护、转义和清理$_GET/$_POST数组的函数,这样您就不必在每次处理用户输入等时处理它。

I was thinking of an function, e.g cleanMe($input), and inside it, it should do mysql_real_escape_string, htmlspecialchars, strip_tags, stripslashes(I think that would be all to make it clean & secure) and then return the $input.

我在想一个函数,例如cleanMe($input),在它里面,它应该做mysql_real_escape_string, htmlspecialchars, strip_tags, stripslashes(我认为这就是让它干净和安全的全部)然后返回$input.

So is this possible? Making a function that works for all $_GETand $_POST, so you would do only this:

那么这可能吗?制作一个适用于所有$_GETand的函数$_POST,因此您只需执行以下操作:

$_GET  = cleanMe($_GET);
$_POST = cleanMe($_POST);

So in your code later, when you work with e.g $_GET['blabla']or $_POST['haha'], they are secured, stripped and so on?

那么在您稍后的代码中,当您使用 eg $_GET['blabla']or 时$_POST['haha'],它们会被保护、剥离等等吗?

Tried myself a little:

自己尝试了一下:

function cleanMe($input) {
   $input = mysql_real_escape_string($input);
   $input = htmlspecialchars($input, ENT_IGNORE, 'utf-8');
   $input = strip_tags($input);
   $input = stripslashes($input);
   return $input;
}

回答by Pekka

The idea of a generic sanitation function is a broken concept.

通用卫生功能的想法是一个破碎的概念。

There is oneright sanitation method for every purpose. Running them all indiscriminately on a string will often break it - escaping a piece of HTML code for a SQL query will break it for use in a web page, and vice versa. Sanitation should be applied right beforeusing the data:

一个适用于各种用途的权利卫生法。在一个字符串上不加选择地运行它们通常会破坏它 - 为 SQL 查询转义一段 HTML 代码将破坏它以在网页中使用,反之亦然。使用数据之前应立即进行卫生处理:

  • before running a database query. The right sanitation method depends on the library you use; they are listed in How can I prevent SQL injection in PHP?

  • htmlspecialchars()for safe HTML output

  • preg_quote()for use in a regular expression

  • escapeshellarg()/ escapeshellcmd()for use in an external command

  • etc. etc.

  • 在运行数据库查询之前。正确的卫生方法取决于您使用的图书馆;它们列在如何防止 PHP 中的 SQL 注入?

  • htmlspecialchars()用于安全的 HTML 输出

  • preg_quote()用于正则表达式

  • escapeshellarg()/escapeshellcmd()用于外部命令

  • 等等等等

Using a "one size fits all" sanitation function is like using five kinds of highly toxic insecticide on a plant that can by definition only contain one kind of bug - only to find out that your plants are infested by a sixth kind, on which none of the insecticides work.

使用“一刀切”的卫生功能就像在一个植物上使用五种剧毒杀虫剂,根据定义只能包含一种虫子——结果却发现你的植物被第六种虫害,而没有杀虫剂的作用。

Always use that one right method, ideally straight before passing the data to the function. Nevermix methods unless you need to.

始终使用一种正确的方法,最好在将数据传递给函数之前直接使用。除非需要,否则不要混合使用方法。

回答by Tomas

There is no point in simply passing the input through all these functions. All these functions have different meanings. Data doesn't get "cleaner" by calling more escape-functions.

简单地通过所有这些函数传递输入是没有意义的。所有这些功能都有不同的含义。通过调用更多的转义函数,数据不会变得“更干净”。

If you want to store user input in MySQL you need to use only mysql_real_escape_string. It is then fully escaped to store safely in the database.

如果要将用户输入存储在 MySQL 中,则只需使用mysql_real_escape_string. 然后完全转义以安全地存储在数据库中。

EDIT

编辑

Also note the problems that arise with using the other functions. If the client sends for instance a username to the server, and the username contains an ampersand (&), you don;t want to have called htmlentitiesbefore storing it in the database because then the username in the database will contain &.

还要注意使用其他功能时出现的问题。例如,如果客户端向服务器发送一个用户名,并且用户名包含一个符号 ( &),则您不希望htmlentities在将其存储到数据库之前调用,因为这样数据库中的用户名将包含&.

回答by Alan Pearce

You're looking for filter_input_array(). However, I suggest only using that for business-style validation/sanitisation and not SQL input filtering.

您正在寻找filter_input_array(). 但是,我建议仅将其用于业务样式的验证/清理,而不是 SQL 输入过滤。

For protection against SQL injection, use parametrised queries with mysqlior PDO.

为了防止 SQL 注入,请使用带有mysqliPDO 的参数化查询。

回答by Arkh

The problem is, something clean or secure for one use, won't be for another : cleaning for part of a path, for part of a mysql query, for html output (as html, or in javascript or in an input's value), for xml may require different things which contradicts.

问题是,对于一个用途来说,干净或安全的东西不会用于另一个用途:清洁路径的一部分、mysql 查询的一部分、html 输出(作为 html,或在 javascript 中或在输入的值中), for xml 可能需要不同的东西,这些东西是矛盾的。

But, some global things can be done. Try to use filter_inputto get your user's input. And use prepared statementsfor your SQL queries.

但是,可以完成一些全局性的事情。尝试使用filter_input来获取用户的输入。并为您的 SQL 查询使用准备好的语句

Although, instead of a do-it-all function, you can create some class which manages your inputs. Something like that :

虽然,您可以创建一些管理输入的类,而不是全能函数。类似的东西:

class inputManager{
  static function toHTML($field){
    $data = filter_input(INPUT_GET, $field, FILTER_SANITIZE_SPECIAL_CHARS);
    return $data;
  }
  static function toSQL($field, $dbType = 'mysql'){
    $data = filter_input(INPUT_GET, $field);
    if($dbType == 'mysql'){
      return mysql_real_escape_string($data);
    }
  }
}

With this kind of things, if you see any $_POST, $GET, $_REQUEST or $_COOKIE in your code, you know you have to change it. And if one day you have to change how you filter your inputs, just change the class you've made.

对于这种情况,如果您在代码中看到任何 $_POST、$GET、$_REQUEST 或 $_COOKIE,您就知道必须更改它。如果有一天您必须更改过滤输入的方式,只需更改您创建的类即可。

回答by Filipe YaBa Polido

May I suggest to install "mod_security" if you're using apache and have full access to server?!
It did solve most of my problems. However don't rely in just one or two solutions, always write secure code ;)
UPDATEFound this PHP IDS (http://php-ids.org/); seems nice :)

如果您使用的是 apache 并且可以完全访问服务器,我可以建议安装“mod_security”吗?!
它确实解决了我的大部分问题。但是不要只依赖一两个解决方案,始终编写安全代码;)
更新发现这个 PHP IDS (http://php-ids.org/); 看上去不错 :)

回答by vuchkov

<?php
function sanitizeString($var)
{
    $var = stripslashes($var);
    $var = strip_tags($var);
    $var = htmlentities($var);
    return $var;
}

function sanitizeMySQL($connection, $var)
{
    $var = $connection->real_escape_string($var);
    $var = sanitizeString($var);
    return $var;
}
?>

回答by user889030

i used that pass array or get , post

我使用了传递数组或获取,发布

function cleanme(&$array)
{ 
 if (isset($array))
 {
     foreach ($array as $key => $value)
     {
          if (is_array($array[$key]))
          {
           secure_array($array[$key]);
          }
          else 
          {
            $array[$key] = strip_tags(mysql_real_escape_string(trim($array[$key])));
          }
     }
 }
}

Usage :

用法 :

cleanme($_GET);   
cleanme($_POST);