Understanding Blacklists and Whitelists with PHP

北战南征 提交于 2019-12-08 11:33:26

问题


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...


回答1:


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.



来源:https://stackoverflow.com/questions/10080682/understanding-blacklists-and-whitelists-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!