Search code examples
phpvalidationerror-handlingwarningsisset

PHP - Custom validator function and passing unset variable


I have a custom validator function which checks different properties of a passed variable including if the variable isset(). However if the variable is not set, the warning is thrown when I call the validator function. The warnings are not displayed and the script runs without a hitch, but I don't want my error log cluttered with all of these entries.

The easy solution is to prefix all of the calls to the function with @, but I'd rather not for obvious reasons. Alternatively I could remove the isset() from the function (or leave it I guess) and instead place the isset() check along side the function call.

I can't see these being the only options; How else can I perform the isset() within the validator function while preventing these warnings from being logged. I'd like to still have undefined variables warnings logged overall, just not when calling this function.

Here is the function:

function validate_data($value, $required = false, $min = false, $max = false, $numeric = false, $email = false){
    if($required === true && (!isset($value) || strlen(trim($value)) < 1) ){
        return false;
    }
    if($min !== false && strlen(trim($value)) < $min){
        return false;
    }
    if($max !== false && strlen(trim($value)) > $max){
        return false;
    }
    if(strlen(trim($value)) > 0 && $numeric === true && (!is_numeric(trim($value)))){
        return false;
    }
    if(strlen(trim($value)) > 0 && $email === true && !filter_var(trim($value), FILTER_VALIDATE_EMAIL)){
        return false;
    }
    return true;
}//validate_data()

Here is an example call:

if(!$someClassName->validate_data($var, true, false, false, false, false)){
    //Do some stuff
}

Solution

  • isset() and empty() are special functions which accept undefined variables without a warning. You cannot create your own function which accepts this.

    But if you work with an undefined variable, you have probably other problems to deal with. Even if not needed in php it is good practise to initialize all variables. A (bad) workaround might be something like this:

    if (!isset($var)) $var = null;