自由文本字段的输入验证

Input-validation for free text fields

我在 PHP 中搜索了很多关于表单验证的内容。不幸的是,所有关于验证机制的教程都是关于特定字段的,比如姓名、邮件或日期。使用正则表达式检查这些字段中的用户输入是否正确很简单。但是检查免费字段(例如联系我们的文本区域或评论字段)的最佳方式是什么?特别是在评论字段中,用户还应该使用 "dangerous" 个字符,例如“<”、“>”或“'”。

处理用户输入的最佳方式是什么?从逻辑上讲,将用户数据纯存储在数据库中不是一个好主意。但屏蔽“<”、“>”或“'”等字符也是个坏主意。

我在 PHP 中看到一个名为 htmlspecialchars() 的函数。很多网站都说用用户输入调用这个函数就足够了。在我看来,如果不进行更多检查,这种解决方案确实有风险。

有没有人对我有任何提示,告诉我如何在不减少 "usability" 的情况下安全地验证我的用户输入?谢谢

But what is the best way to check free fields like a contact-us texteara or a comment field? Specifically in a comment field the user should also use "dangerous" chars like "<", ">" or " ' ".

您可以对每个危险字符使用 if (strpos($string, '<') !== false)(其中 "dangerous" 非常特定于域)。

What is the best way to handle the user input? Logically it's a bad idea to store the user data pure in a database. But it's also a bad idea to block characters like "<", ">" or " ' ".

  1. 为了防止SQL注入,just use prepared statements。 (警告:未模拟准备好的语句。)
  2. 为了防止 XSS,escape on output, never on input.

输入验证没有灵丹妙药。您必须知道您的代码对数据做了什么,才能确定什么是安全的,什么是不安全的。 LDAP 查询与 SQL 查询、XPath 查询或文件系统路径具有不同的安全要求。

如果您出于安全之外的原因正在寻找更通用的输入验证库,Ionizer 值得一试。