Search code examples
phppreg-replacewhitelist

Understanding Blacklists and Whitelists with PHP


I understand that using a whitelist it only uses everything within that list and with a blacklist it uses everything but what is in the list.

But what happens after that? Say your using a whitelist - can you prevent a submission of an input if what the value of the input contains something that wasn't in the whitelist?

I know that something like this would reduce everything that is not a char or digit with whitespace:

preg_replace( "/[^a-zA-Z0-9_]/", "", $stringToFilter );

But what if I didnt want the value stored in the database with whitespace. Is there a way to do this so that an error message occurs instead? using if statements for example...


Solution

  • I understand that using a whitelist it only uses everything within that list and with a blacklist it uses everything but what is in the list.

    • whitelist: items that are approved
    • blacklist: items that are NOT approved

    preg_replace

    You should be using preg_match or filter_var with the flag FILTER_VALIDATE_REGEXP instead...more on this below.

    But what if I didnt want the value stored in the database with whitespace. Is there a way to do this so that an error message occurs instead? using if statements for example...

    You are talking about validation, so you'd be looking at: php.net/filter.filters.validate:

    // false    
    var_dump( !filter_var('string with spaces', FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '/[\s]+/i'))) );
    
    // true
    var_dump( !filter_var('string_with_no_spaces', FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '/[\s]+/i'))) );
    

    Wrap the above in an if statement, and you are done.