【问题标题】:PHP - Filter_var alternative?PHP - Filter_var 替代方案?
【发布时间】:2012-02-03 09:16:35
【问题描述】:

我构建了一个 php 脚本来输出表单中发布的数据,但我遇到了一个问题。网站将运行的服务器运行 PHP 5.1.6。此版本的 PHP 不支持 filter_var。

我需要在短期内(最好是昨天)知道一个替代方案,并且在 Google 或 Stack Overflow 上找不到直接的东西。

也许这里有人过去遇到过同样的问题并为我提供了快速解决方案?

这段代码:

$email= filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$answer= filter_var($_POST['answer'], FILTER_SANITIZE_STRING);

需要与 PHP 5.1.6 兼容,因此会检查电子邮件地址的真实性,并且在任一字段中都没有使用恶意代码。有什么建议吗?

非常感谢!

【问题讨论】:

  • 使用正则表达式代替 filter_var 是唯一的选择。
  • 正则表达式对于简单的文本替换来说有点重。考虑为此目的定义的函数:mysql_real_escape_string()、htmlentities()、addslashes()、....

标签: php sanitize filter-var


【解决方案1】:

对于电子邮件,您可以使用正则表达式:(例如:http://www.totallyphp.co.uk/validate-an-email-address-using-regular-expressions

对于字符串,你也可以使用正则表达式,但这有点太重了,所以如果你将它发送到数据库,可能是 mysql_real_escape_string() 的组合,对于 html,你应该使用 htmlentities()

http://de.php.net/manual/en/function.mysql-real-escape-string.php

http://www.php.net/manual/en/function.htmlentities.php

我不认为 filter_var 函数与仅使用这些方法有很大不同

【讨论】:

  • 谢谢,EGOrecords。我将使用您为电子邮件提供的示例,并将 htmlentities 用于字符串。如果将来有其他人遇到同样的问题,这是一个很好的开始,可以帮助您解决 htmlentities:codeassembly.com/How-to-sanitize-your-php-input
  • ...这真的应该被打勾 =)
【解决方案2】:

您可以通过 PECL 将扩展安装到 PHP 5.1: http://pecl.php.net/package/filter

【讨论】:

  • 如果他不能更新到更新的 PHP 版本,他就不能安装 PHP 扩展(因为你总是需要更深入地访问服务器......)
  • 坦率地说,EGOrecords 是对的。不过,感谢您的意见。 :)
【解决方案3】:

我通常会使用正则表达式。它为您提供最大的灵活性。互联网上有很多关于它的有用资源。看看herehere

【讨论】:

    【解决方案4】:

    使用我在之前的答案中提供的信息,这是我解决问题的方法:

    <?PHP // Retreive POST data and sanitize it: trim string, no HTML, plain text
    $variable1=htmlentities(trim($_POST['input1']), ENT_NOQUOTES);
    $variable2=htmlentities(trim($_POST['input2']), ENT_NOQUOTES);
    $emailaddress=$_POST['email']; // sanitizing email address happens below
    
    if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $emailadres)){    // check email address and if legit, do this:
            echo '<p>The e-mail address given is valid.</p>'
    
    } else{ // if email is not legit, do this:
            echo '<p>The e-mail address given is not valid.</p>';
    }
    ?>
    

    我希望这对某人有帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-17
      • 1970-01-01
      • 1970-01-01
      • 2014-12-30
      • 2020-09-20
      • 2014-06-06
      • 2013-12-22
      相关资源
      最近更新 更多