Question

I am currently experimenting with some universal ways to validate and sanitize my form inputs. Granted there are hundreds if not thousands of ways to do this my particular challenge I've tasked myself with involves my post data and running array_map() right when I bring it in. I have my own custom functions set up that run filter_var() and preg_match() functions as needed on my data after I array_map() while trimming it and then later I run mysqli_real_escape_string() to process it just before I run my SQL. As you will notice I am running htmlspecialchars() over and over again. Is it possible to run a trim and htmlspecialchars at the same time on my post data. I'm going for efficiency so any other recommendations are welcome.

// Trim all the incoming data
$trimmed = array_map('trim', $_POST);

// Assume invalid values
$un = $fn = $ln = $e = $pn = $bio = FALSE;

// Check username
$un = validateUsername(htmlspecialchars($trimmed['uname']));

// Check first name
$fn = validateName(htmlspecialchars($trimmed['fname']));

// Check last name
$ln = validateName(htmlspecialchars($trimmed['lname']));

// Check email address
$e = validateEmail(htmlspecialchars($trimmed['email']));

...etc, etc

Was it helpful?

Solution

Use a custom function in your array_map like this:

function sanitize($input) {
    return htmlspecialchars(trim($input));
}

// Sanitize all the incoming data
$sanitized = array_map('sanitize', $_POST);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top