Best way to clean form data

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
waradmin
Forum Contributor
Posts: 240
Joined: Fri Nov 04, 2005 2:57 pm

Best way to clean form data

Post 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?
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Post 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
SidewinderX
Forum Contributor
Posts: 407
Joined: Fri Jul 16, 2004 9:04 pm
Location: NY

Post 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;
}
User avatar
Mordred
DevNet Resident
Posts: 1579
Joined: Sun Sep 03, 2006 5:19 am
Location: Sofia, Bulgaria

Post 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
Post Reply