I’m having a bit of a problem with escaping data, or at least, the cleanliness of the code involved with it.
Let’s say, I’m escaping a textfield named “FirstName” and it looks something like this:
$FirstName = mysqli_real_escape_string($link, $_POST['FirstName']);
$FirstName = preg_replace( "/[<>#$%]/", "", $FirstName);
$FirstName = preg_replace('/\s\s+/', ' ', $FirstName);
Is there anyway I can just put the last 2 lines in some sort of loop, let’s say like this:
foreach($_POST as $name => $value)
{
$value = preg_replace( "/[<>#$%]/", "", $value);
$value = preg_replace('/\s\s+/', ' ', $value);
}
where then all I have to do later is
$FirstName = mysqli_real_escape_string($link, $_POST['FirstName']);
where $_POST[‘FirstName’] has already been stripped of the other characters?
Sure. Make the
foreachloop by-reference instead of by-value like so:Note the ampersand in front of the
$value. That means the$valueyou get as you iterate over the array is a reference to the value in the array itself rather than a copy of that value.