简体   繁体   中英

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?

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.

In the example below, the input variable "email" is sent to the PHP page:

I think it's best to use client-side validation using HTML5 then use server-side. 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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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