Page 1 of 1

PHP side form validation and sanitization

Posted: Sat Nov 19, 2011 9:57 am
by Live24x7
Am stuck with php side form validation. My requirement are as follows:

An HTML form (say: form.php) sends the following fields:

Code: Select all

$rname=$_POST['rname']; 
$rmobile=$_POST['rmobile']; 
$rarea=$_POST['rarea']; 
$remail=$_POST['remail']; 
I have no issues this far.
Before I insert these fields into the sql database, here's what i want to do:
  • 1) Check if all 5 fields are filled
    2) Check if rmobile is a ten digit number
    3) Check if email is in the proper format
If these do not validate, i want to resend the user to form.php along with msg "Please correct the errors in the form and submit again"

If they validate, the php code should trim and sanitize the data before inserting into the SQL database.

Please help me with the php code for the validation/ trimming and sanitization part.

I have been pulling my hair on this one
PLs Pls Pls get me out of this :(

Re: PHP side form validation and sanitization

Posted: Sat Nov 19, 2011 10:45 am
by Celauran
Quick and dirty:

Code: Select all

$errors = array();
$required = array('rname', 'rmobile', 'rarea', 'remail');

if (!empty($_POST))
{
    foreach ($required as $req)
    {
        if (!array_key_exists($req, $_POST))
        {
            $errors[] = "{$req} must be completed.";
        }
    }

    $_POST['rmobile'] = str_replace("-", "", $_POST['rmobile']);
    $_POST['rmobile'] = str_replace(".", "", $_POST['rmobile']);

    if (!ctype_digit($_POST['rmobile']))
    {
        $errors[] = "Mobile number must contain only digits.";
    }

    if (!filter_var($_POST['remail'], FILTER_VALIDATE_EMAIL))
    {
        $errors[] = "Email address does not appear to be valid.";
    }

    foreach ($_POST as $k => $v)
    {
        $_POST[$k] = mysql_real_escape_string($v);
    }
}

if (!empty($_POST) && empty($errors))
{
    // Process form
}

Re: PHP side form validation and sanitization

Posted: Sat Nov 19, 2011 11:21 pm
by Live24x7
thanks a lot. Got it.

There is one small issue though.

If the fields are empty or there are errors, i am able to send then back to form.php using header (Location:form.php) but I am not being able to display the message
"Please correct the errors in the form and submit again"

Is there a way of achieving this without using session ?

rgds

Re: PHP side form validation and sanitization

Posted: Sat Nov 19, 2011 11:33 pm
by twinedev
Live24x7 wrote:Am stuck with php side form validation.
Server-side validation should ALWAYS be done. You cannot trust anything coming from the client.

Re: PHP side form validation and sanitization

Posted: Sun Nov 20, 2011 6:25 am
by social_experiment
Live24x7 wrote:If the fields are empty or there are errors, i am able to send then back to form.php using header (Location:form.php) but I am not being able to display the message
"Please correct the errors in the form and submit again"

Is there a way of achieving this without using session ?
You could call the form on itself, by setting the action attribute of the form to "". This would let you display the error message/s on the same page as the form.

Code: Select all

<?php
 // place the code where you want the error message to display
 if (isset($_POST['yourSubmitButtonName'])) {
  // check for errors and echo the messages
 }
?>

Re: PHP side form validation and sanitization

Posted: Sun Nov 20, 2011 12:27 pm
by Live24x7
thanks @ social experiment for pointing me in the right direction. I could achieve what i wanted.

I need one more help. I now need to sanitize the data before it makes it way to the sql table.
So far i have used trim(), stripslashes() htmlspecialchars() and mysql_real_escape_string() functions.

Is there a similar function to prevent php code injection through the form.

For e.g,

in the rname field, if i enter a <?php ?>, it still making its way to the database after passing through all these filters.

I tried somethings on this line, but it wont prevent the code from getting into database

Code: Select all


	                                 filter_var("$rname", FILTER_SANITIZE_STRIPPED);
					filter_var("$remail", FILTER_VALIDATE_EMAIL);  
					filter_var("$rmn", FILTER_SANITIZE_NUMBER_INT);  
					filter_var("$rarea", FILTER_SANITIZE_STRIPPED);
					// Insert into DB after sanitization
					mysql_query("INSERT INTO table1 VALUES ('$rname', '$rbg', '$rmn','$rarea', '$remail')"); 


 

Re: PHP side form validation and sanitization

Posted: Sun Nov 20, 2011 12:34 pm
by Celauran
Something is definitely wrong if <?php ?> tags are making it through strip_tags.

Code: Select all

<?php
$str = "<?php foo bar baz; ?>";
var_dump(strip_tags($str));
?>
should produce

Code: Select all

string (0) ""

Re: PHP side form validation and sanitization

Posted: Sun Nov 20, 2011 1:40 pm
by Live24x7
i haven't used strip_tags.
I have used stripslashes

So u suggesting, I should use strip_tags ??
I will give it a try.

Thanks

Re: PHP side form validation and sanitization

Posted: Sun Nov 20, 2011 1:52 pm
by Live24x7
@Celauran

even strip_tags does not prevent the <?php Hell ?> from getting into the database.Here's how I am trying it

Code: Select all


function check_input($data) //custom function to trim, stripslash and remove html chars
				{ 
                                 $data = trim($data);return $data; 
                                  $data = strip_tags($data); return $data; // added this after your last post - still allowing <? ?> to get through
                                   $data = stripslashes($data); return $data; 
                                    $data = htmlspecialchars($data);return $data; 
                                   mysql_real_escape_string($data); return $data; 
                                    } 

				$rname= check_input($_POST['rname']); 
				$rbg= check_input($_POST['rbg']); 
				$rmn= check_input($_POST['rmn']); 
				$rzip= check_input($_POST['rzip']); 
				$remail= check_input($_POST['remail']); 

mysql_query("INSERT INTO table1 VALUES ('$rname', '$rbg', '$rmn','$rzip', '$remail')"); 
Any pointers ?

Re: PHP side form validation and sanitization

Posted: Sun Nov 20, 2011 8:53 pm
by Celauran
Live24x7 wrote:even strip_tags does not prevent the <?php Hell ?> from getting into the database.
Then something is broken. That's the whole purpose of strip_tags().

... and I found what is broken.

Code: Select all

function check_input($data) //custom function to trim, stripslash and remove html chars
{
    $data = trim($data);return $data;
    // You've returned, so nothing below this line ever gets executed.
    $data = strip_tags($data); return $data;
    $data = stripslashes($data); return $data;
    $data = htmlspecialchars($data);return $data;
    mysql_real_escape_string($data); return $data;
}

Re: PHP side form validation and sanitization

Posted: Sun Nov 20, 2011 11:21 pm
by twinedev
The problem is that in your function, the very first line you are calling:

Code: Select all

return $data;
This exits the function and never does any further processing. You need to only have this at the END of your function.
Additionally, the last line you currently have which calls mysql_real_escape_string() does not assign that back to $data, need to add $data = to the beginning of that line.

-Greg

PS. Missed that Celauran had posted the first part as a comment inside the code sniplet he posted ;-)

Re: PHP side form validation and sanitization

Posted: Mon Nov 21, 2011 1:46 am
by Live24x7
@Celauran - thanks.. think i am too old to writing codes :roll:

@twinedev - thanks a lot for pointing out the second issue.
If only PHP understood what was supposed.

Here's my last question before this thread gets too wild.
So far, In my attempt at sanitization, i have used:
  • preg_match () // for each individual field in the form
    trim()
    strip_tags()
    stripslashes()
    htmlspecialchars()
    mysql_real_escape_string()

My question:

Are these enough ?
Any other thing that could be possible added to keep hooligans away ?

Re: PHP side form validation and sanitization

Posted: Mon Nov 21, 2011 2:05 am
by social_experiment
Live24x7 wrote: preg_match () // for each individual field in the form
trim()
strip_tags()
stripslashes()
htmlspecialchars()
mysql_real_escape_string()
I'd remove stripslashes() and htmlspecialchars(). stripslashes() because it would remove slashes from data, which IMO is pointless because an attacking string doesn't use slashes to escape data in it; also, if there are no slashes to strip you are using the function for no reason adding to processing time. Note: Anyone aware of attacks utilizing slashes? Directory traversal attacks? Had a quick look at this URL https://www.owasp.org/index.php/File_Sy ... _traversal but couldn't spot any specific reference to stripslashes()

Secondly, htmlspecialchars() would be better used to display your data and prevent XSS (cross-side scripting attacks).

Re: PHP side form validation and sanitization

Posted: Mon Nov 21, 2011 5:31 am
by Live24x7
@social experiment: thanks very helpful information and URL resource :o