Validate before submit?

Security issues related to php and mysql usage. How to make your code secure? Security measures and configurations? It's all in here!

Moderators: macek, egami, gesf

New php-forum User
New php-forum User
Posts: 1
Joined: Fri May 13, 2011 11:59 am

Validate before submit?

Postby themaelane » Fri May 13, 2011 12:15 pm

I'm still fairly new at php, and am trying to make sure I've got a full and proper understanding of site security.

My first question is this:
Say I have a form like below in a file called form.php..

Code: Select all

<FORM ACTION="<?php echo($form_result); ?>" METHOD="post">
Your name: <input type="text" name="fdbk_name" maxlength="40" /><br />
Your company: <input type="text" name="fdbk_company" maxlength="40" /><br />
Your email address: <input type="text" name="fdbk_email" maxlength="40" /><br />

At the top of the page I called:

Code: Select all

$form_result = feedbackform.php

I've read that you need to make sure that all variables need to be validated before use. So does that mean that I can't even submit the form to another page (feedbackform.php) where it is immediately validated? Do I need to do validation within form.php before going onto feedbackform.php....where I have to validate it again?

If I have to do it within itself, would this work:
$form_result = htmlspecialchars($_SERVER['PHP_SELF']);
.....but then how do I send it onto another php page if validation succeeds?

Thanks for your help!

User avatar
php-forum GURU
php-forum GURU
Posts: 2196
Joined: Wed Oct 06, 2010 11:19 am
Location: Happy Valley, UT

Re: Validate before submit?

Postby egami » Mon May 16, 2011 7:04 am

There are two ways to do form validation. And only one of them is a for sure way of cleansing.

The first is by using Javascript. But if said browser has JS disabled, then there isn't any validation.
So, using PHP to validate takes up server side resources, but it's the only way to really validate the input.

The first thing I would do is create an array of the items you want to validate.

1. Remember that variables are CaSe sensitive.
2. Create an array of all of the inputs you want to validate.
- ie.. $array = array('dbk_name','fdbk_company','fdbk_email');

3. Then iterate through the array and do a general check and remove nonsense from the input..

Code: Select all

foreach($array as $k => $v) { 
$_POST[$k] = trim(strip_tags(mysql_real_escape_string($_POST[$k])));

This is a basic cleansing to remove any kind of HTML/PHP/SQL injections.

4. If you want to take it a step further.
$fdbk_name = preg_replace('/[^a-zA-Z\-\']/','',$_POST['fdbk_name']);
// this removes numbers, html special chars and tags, and only leaves the alphabet, a dash and apostrophe.

Check for more information on cleaning your other variables.
The email checking/validation will be the trickiest.

Return to “PHP & MySQL Security”

Who is online

Users browsing this forum: No registered users and 2 guests