Whitelisting: You Set The Rules For Security

By  on  

We all know what blacklisting is when it comes to strings: removing specified "bad" characters. While this helps to secure user input, it isn't as secure as whitelisting. Whitelisting is the process of saying "Let me tell you what you can give me" whereas blacklisting says "If I find this, I'll remove it."

A customer recently asked that I create a whitelisting function that allowed letters, digits, whitespace characters, periods, commas, and dashes. Any other characters were to be replaced with spaces.

The PHP

function make_valid($input) 
{ 
	return preg_replace('/[^A-Za-z0-9.,\(\)\s-]/',' ',$input); 
}

The above function uses preg_match() and a small regular expression to remove the rubbish characters.

Recent Features

  • By
    CSS @supports

    Feature detection via JavaScript is a client side best practice and for all the right reasons, but unfortunately that same functionality hasn't been available within CSS.  What we end up doing is repeating the same properties multiple times with each browser prefix.  Yuck.  Another thing we...

  • By
    CSS Gradients

    With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements.  CSS gradients are another step in that direction.  Now that CSS gradients are supported in Internet Explorer 8+, Firefox, Safari, and Chrome...

Incredible Demos

  • By
    Build a Calendar Using PHP, XHTML, and CSS

    One of the website features my customers love to provider their web users is an online dynamic calendar. An online calendar can be used for events, upcoming product specials, memos, and anything else you can think of. I've taken some time to completely...

  • By
    Multiple File Upload Input

    More often than not, I find myself wanting to upload more than one file at a time.  Having to use multiple "file" INPUT elements is annoying, slow, and inefficient.  And if I hate them, I can't imagine how annoyed my users would be.  Luckily Safari, Chrome...

Discussion

  1. Your way for whitelisting is quite nice. It’s like in Flash where you can specify exactly what characters are allowed by the user.
    This method may work well as a common security filter that replaces get_magic_quotes_gpc(), strip_tags() and htmlentities().
    Good work as usual!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!