How to Validate Post Variables or File Variables in PHP

Hello everyone....

This post will assist you in validating POST and FILES variables. You can also change them to use GET variables.

First, as shown below, we will create a helper function.

function RequiredFields($post_fields,$file_fields="")
{ 
    foreach (explode(",",$post_fields) as $key => $value) { 
        if (!isset($_POST[$value])) {
            $res["error"]="1";
            $res["message"]=$value." field is missing.";
            echo json_encode($res);
            exit;
        }
    } 
    if ($file_fields!='')
      {
        foreach (explode(",",$file_fields) as $key => $value) { 
            if (!isset($_FILES[$value])) {
                $res["error"]="1";
                $res["message"]=$value." field is missing.";
                echo json_encode($res);
                exit;
            }
        }
    } 
}

Then, after importing the helper, simply use the function as shown below in every function required in the controller. 

 RequiredFields("varable_name");

Thank you...

Tagged:
Sign In or Register to comment.