I have this code which sanitises user input on a variable called ‘username’:
$username_clean = preg_replace( "/[^a-zA-Z0-9_]/", "", $_POST['username'] );
if (!strlen($username_clean)){
die("username is blank!");
I want to carry out the same process on each input on this page but I have about 12 different inputs since it is a registering form. Is there an easier way to sanitise and check each input instead of applying preg_replace() and the if statement on each one?
If you want to sanitize all of the elements in
$_POST, then you could just create a sanitization function and apply it to all the elements witharray_map:Then you’d access your variables via
$post_cleaninstead of$_POST.It’d look something like:
If you only wanted to sanitize a subset of the
$_POSTelements, you could do something like:Try this:
Just make sure to change $sanitize_keys to an array of whatever variables (or $_POST keys) you want to sanitize.