Page 1 of 1

Best way to clean form data

Posted: Tue Dec 11, 2007 5:22 pm
by waradmin
I have a site that takes form data from many fields, and I want to protect myself from the bad apples out there. What is the best way to do this? Currently I am doing:

Code: Select all

function cleanInput($aString)
{
	$aString = strip_tags($aString);
	$aString = str_replace("<","", $aString);
	$aString = str_replace(">","", $aString);
	$aString = str_replace("'","", $aString);
	$aString = str_replace("/","", $aString);
	$aString = str_replace("","", $aString);
	$aString = str_replace("(","", $aString);
	$aString = str_replace(")","", $aString);
	$aString = str_replace(",", " ", $aString);
	$aString = str_replace("  ", " ", $aString);
        $aString = str_replace("#","%23", $aString); 
        $aString = str_replace("'","`", $aString); 
        $aString = str_replace(";","%3B", $aString); 
        $aString = str_replace("script","", $aString); 
        $aString = str_replace("%3c","", $aString); 
        $aString = str_replace("%3e","", $aString); 
        $aString = str_replace("@", "[at]", $aString);
        $aString = trim($aString);
	return($aString);
}
Which I know is quite messy, is there a better way to clean input because I think I am doing it all wrong.

And as far as MySQL injections go, are they also done through form input boxes or are they done using a different method?

Posted: Tue Dec 11, 2007 6:31 pm
by califdon
At the very least, you could use regular expressions, but there is in fact a whole lot of information on validating user input. You can start with viewtopic.php?t=73917&highlight=data+input+validation

Posted: Wed Dec 12, 2007 3:18 pm
by SidewinderX
I tend to do something like the following:

Code: Select all

function cleanInput($aString) { 
	$patterns = array("/\&/", "/%/", "/</", "/>/", '/"/', "/'/", "/\(/", "/\)/", "/\+/", "/-/");
	$replacements = array("&", "& #37;", "<", ">", """, "& #39;", "& #40;", "& #41;", "& #43;", "& #45;");
	$cleaned = preg_replace($patterns, $replacements, $aString);	
return $cleaned;
}

Posted: Thu Dec 13, 2007 8:40 am
by Mordred
Both solutions are wrong in both idea and implementation. Don't cook your own security measures, use the well-tested ones.
User input should be escaped, not crippled.
viewtopic.php?t=75098