Jump to content

Best way to clean a lot of inputs?


Rifts

Recommended Posts

Hey guys

 

I have a lot of inputs from my form. Is there a way I can do like a for each or something instead of of having to write

 

$myusername = stripslashes($_POST['name');

$mypassword = stripslashes($_POST['pass']);

$myusername = mysql_real_escape_string($myusername);

$mypassword = mysql_real_escape_string($mypassword);

 

.... for all 16 fields?

 

thanks

Link to comment
https://forums.phpfreaks.com/topic/221257-best-way-to-clean-a-lot-of-inputs/
Share on other sites

write a function? =P

 

function clean($var){
$var=stripslashes($var);
$var=mysql_real_escape_string($var);
return $var;
}

foreach($_POST AS $row){
$my[]=clean($row);
}

print_r($my);

 

^ not sure if foreach $_POST is a good idea... at least check if it exists first! xD

 

if the input fields had been named similar, like: my1, my2 etc. then you could just have

 

for($i=1;$i<17;$i++){

$my[]=clean($_POST['my'.$i]);

}

Sometimes I set up an array of variable names, then loop over that. something like (simplified)

 

$pvars = array('fname','lname','address1','city','state','zip');

foreach ($pvars AS $a_pvar) {
     ${$a_pvar} = mysql_real_escape_string(strip_slashes($_POST[$a_pvar]));

}

 

I don't simply loop over POST, because it scares me.

Sometimes I set up an array of variable names, then loop over that. something like (simplified)

 

$pvars = array('fname','lname','address1','city','state','zip');

foreach ($pvars AS $a_pvar) {
     ${$a_pvar} = mysql_real_escape_string(strip_slashes($_POST[$a_pvar]));

}

 

I don't simply loop over POST, because it scares me.

 

ye!

 

so I also suggested:

 

if the input fields had been named similar, like: my1, my2 etc. then you could just have

 

for($i=1;$i<17;$i++){

  $my[]=clean($_POST['my'.$i]);

}

Or if you sometimes use arrays and don't want to remove \ that are intentionally part of the data -

function escape_deep($value){
if(is_array($value)){
	$value = array_map('escape_deep', $value);
} else {
	if(get_magic_quotes_gpc()){
		$value = stripslashes($value);
	} else {
		$value = mysql_real_escape_string($value);
	}
}
    return $value;
}

$_POST = array_map('escape_deep', $_POST); // escape all the post data at once

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.