Jump to content

Recommended Posts

Started a new topic since the main question on my other thread was answered.

 

I've already validated my form with jquery. Now I am doing server side to scrub the data and provide security.

 

I pretty much understand what I need to do for most of the fields. IE I've got a function to check the email address.

 

What about something like a drop down menu for states? The values are all 2 letter abbreviations.

 

For Gender I have radio buttons-- would:

 

if ($gender != "male" || $gender != "female"){ 
echo "Please select your gender";
exit;
}

 

Cover my bases?

 

I also have a whole page of options which are optional. I obviously want to prevent any exploitation there. Beyond stripping html, slashes, and trimming is there anything I should do to optional entries?

 

There are about 30 questions on this form so I am trying to be efficient but thorough.

 

Thanks a lot-- this board is always the most helpful I can find!

Link to comment
https://forums.phpfreaks.com/topic/187809-server-side-validation/
Share on other sites

you need to test EVERY value that is coming to make sure it is what you expect it to be.  If its a integer then test for it.  If its a date then checkdate() it.  It doesn't matter if its a dropdown or checkbox.  If its coming in from the public-validate it.  I use the form validator class from http://www.html-form-guide.com/php-form/php-form-validation.php.  Its really good and you can write custom rules for it.

Right, I understand I need to check everything-- I just don't know HOW. I mean I have some basic ideas, but some of the fields are problematic for me.. for example the select field I mentioned. Also Street Address.. I can check if it's null, but other than that what can I do to prevent malicious stuff from that field?

 

I am checking out the script you linked now

 

Thanks

well think about what rules you will have for each input. as tom stated, for integer values, you should check if they are integers (is_int() will help with that)

 

as for your specific example a street address starts with a number, and has a word. you can use regex functions like preg_match() to make sure its of the correct format.

 

also, make sure you use mysql_real_escape_string() on all non encrypted data that you insert into the database to protect against sql injection.

 

by the way, if there is a function that you end up applying to all the post data (IE if you use real escape string on everything) instead of doing every single entry individually, you can use array_map() to do it in 1 line.

 

an example of its usage

//apply mysql_real_escape_string() to every piece of data in the $_POST array
$_POST = array_map('mysql_real_escape_string', $_POST);

 

alternatively, if you are using $_GET you would obviously replace $_POST with $_GET

Thanks

 

For State I was thinking build an array of the values in the drop down and test if it matches?

 

Street Address I don't think a regex will really work. There are so many variations. Mostly I want to make sure something is entered and that it isn't something malicious. If it's a fake address.. oh well as long as it doesn't F my data up. Does that make sense?

 

Stuff like zipcode I have down, along with how to make sure something required is there. The optional stuff and check boxes confuse me.

 

I've got about a dozen questions that have check boxes or multiple values-- all are optional. Should I make arrays with each possibly answer and test them? That would be kind of bloated wouldn't it?

 

Also I am using postgre will running my data through pg_query_params() sufficiently protect against injections? I have seen claims for and against it

with that class i posted the link to you can test for anything.  Like length, numeric, alphanumeric, and combinations.  You can also make your own functions and put into the class so they will get tested.

 

 

Here is some code using the forms validator class that I use in a form

 

first require() the formsvalidator.php class at the top of you script.

 

 

Use function with:

 

list($ValidateError, $ValidationMsg) = _add_ValidateForm();

//test for error
if (isset($_POST['submit']) && !empty($ValidateError))
{
//error was found
echo $ValidationMsg;

}
else
{
// no errors, ok to save to db

}

 

 

 

put function below at bottom of script

 

function _add_ValidateForm()
{
    if (isset ($_POST['submit']))
    {
        $validator = new FormsValidator();
        // Validation types for this form go here **********
        // Fields that are required and cannot be empty
        $validator->addValidation('firstname', 'req', 'Customer First Name cannot be blank. Please re-enter.');
        $validator->addValidation('lastname', 'req', 'Customer Last Name cannot be blank. Please re-enter.');
        $validator->addValidation('address', 'req', 'Address 1 cannot be blank. Please re-enter.');
        $validator->addValidation('city', 'req', 'City cannot be blank. Please re-enter.');
        $validator->addValidation('zip', 'req', 'Zip code cannot be blank. Please re-enter.');
        $validator->addValidation('email', 'req', 'E-mail cannot be blank. Please re-enter.');
        // Other checks
        //$validator->addValidation('firstname', 'alnum_s', 'Customer First Name is invalid. Please  re-enter alphanumeric characters only.');
        //$validator->addValidation('lastname', 'alnum_s', 'Customer Last Name is invalid. Please  re-enter alphanumeric characters only.');
        $validator->addValidation('city', 'minlen=3', 'City is invalid. Please re-enter.');
        $validator->addValidation('city', 'alnum_s', 'City is invalid. Please re-enter.');
        $validator->addValidation('state', 'alnum_s', 'State is invalid. Please re-enter.');
        $validator->addValidation('phone', 'num', 'Phone Number must be Digits Only.  Please re-enter.');
        $validator->addValidation('phone', 'lenreq=10', 'Phone Number must be 10 digits. Please re-enter.');
        $validator->addValidation('email', 'email', 'E-mail adress is not valid.  Please re-enter.');
        $validator->addValidation('zip', 'zipcode', 'Zip code is not valid.  Please re-enter.');
        $validator->addValidation('zip', 'maxlen=10', 'Zip code is not valid.  Please re-enter.');
        $validator->addValidation('routing', 'routing', 'Bank Routing Number is invalid.  Please re-enter.');
        $validator->addValidation('account', 'num', 'Account Number must be Digits Only.  Please re-enter.');
        $validator->addValidation('account', 'minlen=3', 'Account Number is invalid. Please re-enter.');
        $validator->addValidation('account', 'eqelmnt=account0', 'Bank Account Numbers do not Match. Please re-enter.');
        // End Validation Types ***************************
        // if a validation fails, return the first error.
        // This will keep going until all validations pass
        if (!$validator->ValidateForm())
        {
            $ValidateError = true;
            $error_hash = $validator->GetErrors();
            foreach ($error_hash as $varname => $var_error)
            {
                $ValidationMsg = $var_error;
                break;
            }
        }
        //end if
    }
    // end if
    return array($ValidateError, $ValidationMsg);
}
//end function

 

 

 

As far as something like a street address you would think about what type of value you would expect that to be and make sure thats what you are going to accept.  It would be alpha numeric with spaces at the very least.  You will probably find that you will tweak your validation as you go. Tightening up in some places and loosening up in others.

...if there is a function that you end up applying to all the post data (IE if you use real escape string on everything) instead of doing every single entry individually, you can use array_map() to do it in 1 line.

 

an example of its usage

//apply mysql_real_escape_string() to every piece of data in the $_POST array
$_POST = array_map('mysql_real_escape_string', $_POST);

 

alternatively, if you are using $_GET you would obviously replace $_POST with $_GET

 

If you apply multiple functions to a single input then create a new function something like:

function clean($value) {
    $value = trim($value);
    $value = strip_tags($value);
    $value = addslashes($value);
    if ($temp = @mysql_real_escape_string($value)) $value = $temp; // PHP Manual: mysql_real_escape_string: Returns the escaped string, or FALSE on error. 
    return $value;
}

$_POST = array_map('clean', $_POST);

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.