简体   繁体   English

验证和清理PHP中的用户输入

[英]Validating and Sanitizing user input in PHP

Is it considered best practice to use filter_var() and sanitize_var() offered by PHP to filter and sanitize variables, or are there better options? 是否使用PHP提供的filter_var()sanitize_var()来过滤和清理变量是最佳实践,还是有更好的选择?

Thank you. 谢谢。

Let's try validating input from a form. 让我们尝试验证来自表单的输入。

The first thing we need to do is to confirm that the input data we are looking for exists. 我们需要做的第一件事是确认我们正在寻找的输入数据是否存在。

Then we filter the input data using the filter_input() function. 然后,我们使用filter_input()函数过滤输入数据。

In the example below, the input variable "email" is sent to the PHP page: 在下面的示例中,输入变量“ email”被发送到PHP页面:

I think it's best to use client-side validation using HTML5 then use server-side. 我认为最好先使用HTML5进行客户端验证,然后再使用服务器端。 PHP has functions like FILTER_SANITIZE_STRING (although you don't need to validate that) that filters strings and you can use FILTER_VALIDATE_EMAIL rather than manually validate emails using regex. PHP具有过滤字符串的功能,例如FILTER_SANITIZE_STRING(尽管您无需验证),您可以使用FILTER_VALIDATE_EMAIL而不是使用正则表达式手动验证电子邮件。 You can also use restrictions such as how much characters so on. 您还可以使用限制,例如字符数等等。

Example conceptually... 概念上的例子...

if form is submitted 
  if 'name' is not empty
    create a variable that equals filter_var($_POST['name'], FILTER_SANITIZE_STRING)
    if 'name' is empty then set echo an error message

  if 'email is not empty
    create a variable that equals filter_var($_POST['email'], FILTER_SANITIZE_STRING)
    // then you can validate email
    if (!filter_var($email, FILTER_VALIDATE_EMAIL))
      error message
  // do this for other variables

  if there's not error
    send email and or a thank you message

 //FORM here

我将始终考虑以下原则...“从不信任用户输入” ctype_alpha,ctype_alnum也是验证的良好执行者,并且记住也要验证客户端(javascript验证),这也将有助于减轻服务器负载

I'd like to mention HTML Purifier for any HTML filtering / clean-up. 我想提到HTML Purifier用于任何HTML过滤/清理。

For generic validation (numeric, date and other values) there are plenty of libraries out there, there are also built in functions, it's your choice to pick the most appropriate, but I'd still like to mention Zend_Validate if you already use Zend Framework. 对于通用验证(数字,日期和其他值),有很多库,也有内置函数,您可以选择最合适的库,但是如果您已经使用过Zend Framework,我仍然要提及Zend_Validate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM