Search code examples
phpsanitizationwhitelist

Sanitisation on user input using whitelist


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?


Solution

  • 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 with array_map:

    $post_clean = array_map("sanitization_function", $_POST);
    

    Then you'd access your variables via $post_clean instead of $_POST.

    It'd look something like:

    function sanitize($dirty){ 
        return preg_replace( "/[^a-zA-Z0-9_]/", "", $dirty ); 
    }
    
    $cPOST = array_map("sanitize", $_POST);
    
    if (!strlen($cPOST['username'])){ 
        die("username is blank!"); 
    }
    

    If you only wanted to sanitize a subset of the $_POST elements, you could do something like:

    $cPOST = array();
    $sanitize_keys = array('username','someotherkeytosanitize');
    foreach($_POST as $k=>$v)
    {
        if(in_array($k, $sanitize_keys))
        {
            $cPOST[$k] = preg_replace( "/[^a-zA-Z0-9_]/", "", $v);
        }
        else
        {
            $cPOST[$k] = $v;
        }
    }
    

    Try this:

    $cPOST = array();
    $sanitize_keys = array('username','someotherkeytosanitize');
    for($_POST as $k=>$v)
    {
        if(in_array($k, $sanitize_keys))
        {
            $cPOST[$k] = preg_replace( "/[^a-zA-Z0-9_]/", "", $v);
            if(strlen($cPOST[$k]) == 0){ 
                die("%s is blank", $k);
            }
        }
        else
        {
            $cPOST[$k] = $v;
        }
    }
    # At this point, the variables in $cPOST are the same as $_POST, unless you 
    # specified they be sanitized (by including them in the $sanitize_keys array.
    # Also, if you get here, you know that the entries $cPOST that correspond
    # to the keys in $sanitize_keys were not blank after sanitization.
    

    Just make sure to change $sanitize_keys to an array of whatever variables (or $_POST keys) you want to sanitize.