【问题标题】:preg_match include forward slashpreg_match 包括正斜杠
【发布时间】:2012-08-18 06:13:08
【问题描述】:

这是检查输入的安全问题和/或答案是否包含恶意字符的功能:

function validate_input($field) {
    $ErrorMessage = ""; 
    $field = preg_replace("/[\s]+is/", '', $field);
    if(preg_match("/^[A-Za-z0-9'?!-\s]+$/", $field ) ===0) {
        $ErrorMessage .= "<div class='error_message'>Potentially malicious characters found in:<i> " . $field . ",</i> please enter only alphanumeric characters</div/><br/>";
    } return $ErrorMessage;
}

当我输入“怎么了?”之类的内容时对于这个问题,它返回一个错误。当我在 ($field) 上执行 var_dump 时,它会返回“What\'s up?”。

那么如何将正斜杠作为可接受的字符包含在内?

【问题讨论】:

  • 您是否在检查“恶意字符”以防止 SQL 注入?
  • 你应该停止使用mysql_*函数。它们正在被弃用。请改用PDO(PHP 5.1 起支持)或mysqli(PHP 4.1 起支持)。如果您不确定使用哪一个,read this article。当您在其中使用准备好的语句时,它们将有助于防止 sql 注入,从而使您的上述代码变得不必要。

标签: php regex preg-match


【解决方案1】:

您似乎拥有 PHP 的“魔术报价”功能,这不应该是出于安全原因:用户插入数据的所有转义都应该由您自己的代码完成。

无论如何,如果您想保持现在的状态,请更换您的

preg_match("/^[A-Za-z0-9'?!-\s]+$/", $field)

preg_match("/^[A-Za-z0-9'?!-\s\\\\]+$/", $field )

存在四重 \ 是因为您需要将其转义,因为您需要在用双引号分隔的字符串中和在正则表达式中。

【讨论】:

    【解决方案2】:

    允许正斜杠和其他普通字符的示例。

        $string = "J’s Bikes/IHOP";  // bad user input 
        if (!preg_match("/^[A-Za-z0-9!@#$%&()*;:_.'\/\\\\ ]+$/", $string)) {
           echo "Invalid $string";          
           }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      • 2011-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-14
      • 2021-05-29
      相关资源
      最近更新 更多