Search code examples
phpsanitization

Sanitize $_POST and $_GET array inputs OOP


I have this code from a class method that I want to use to treat the data before pass them to the database. I'm not sure on how to proceed, this because usually I prefer to use ajax and a non OOP controller to sanitize the various data. I'm not sure if use filter_var_array or filter_input_array to achieve this task. If anyone has a suggestion about this task, I will appreciate it.

Here is an example of my code:

<?php

class UserRegistration{

  public function registration($data = null){
    echo $this->view->registrationForm();

    if( isset($_POST['register']) ){
      $data = [
        $_POST['username'],
        $_POST['email'],
        password_hash($_POST['password'], PASSWORD_BCRYPT, ['cost'=>11])
      ];

      if( $this->sanitizeData($data) ){
        echo $this->view->registrationSuccess();
      }
    }

  }

  private function sanitizeData(array $data){
    $args = ['username'=> FILTER_SANITIZE_STRING, 'email'=> FILTER_SANITIZE_EMAIL, 'password'=> FILTER_SANITIZE_STRING ];
    $sanitized_data = filter_var_array($data, $args);
    return $sanitized_data;
  }

}
?>

Solution

  • You don't need sanitize data before saving it to the database. More info here https://security.stackexchange.com/questions/95325/input-sanitization-vs-output-sanitization