Thursday, August 24, 2017

PHP Form Validation Part 1

Form Validation is used to validate form data, Protect against hackers and Spammers. We can Validate User's input on the Client Side and on the server side. In this article, we'll discuss why validation is important and how to secure the web form in PHP.

Why validation is important?

Submit form without validating data means you are inviting to the someone destruct your website by using hacking techniques.

How to Secure Web form in PHP

We need to make one Validation layer (function or class) before the user's form data is used in the script or stores the database. This layer validates each form input and pushes into $_POST or $_GET.  if you are not using any PHP framework so definitely you need to write some custom validation code. It could be a bunch of function or a class. Make one Validation class is good to approach rather than an individual method.

Never assign form input directly to class property or local variable it could be harmful.

$val = $_POST['val'];

For securing let's make a validation class.

class formValidation{

     public function __construct(){        
      //secure Post request
      $this->post();
      //secure Get request
      $this->get();
     }

     public function post(){
      $post = $_POST;
         $this->userInput($post,'post');
     }
     
     public function get(){
       $get = $_Get;
        $this->userInput($get,'get');
    }

    private function userInput($data,$type){
    $arg = [];
     // clean user input logic here 
     foreach($data as $k => $val): 
      $val = trim($val);
      $val = stripslashes($val);
      $val = htmlspecialchars($val);
      $arg[$k] = $val;   
     endforeach;
    
  if($type = 'post'):
       $_POST = $arg;
     endif;

  if($ype = 'get'):
      $_GET = $arg;
    endif;
   }
    
}

That's a very simple class having three method's two of the public and one is private. let's initialize form validation class.

$formValidation = new formValidation();

Whenever you initialize form validation class into other classes or inherit with it. it will automatically remove whitespaces at the start and at the end, remove backslashes and convert each form field data into HTML entities. So in the end, you have learned about how to secure web form. In the next Article, you will learn about how to restrict the user to don't send empty input, less than or greater characters stuff.

0 comments:

Post a Comment