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
    39 Shirts – Leaving Mozilla

    In 2001 I had just graduated from a small town high school and headed off to a small town college. I found myself in the quaint computer lab where the substandard computers featured two browsers: Internet Explorer and Mozilla. It was this lab where I fell...

  • By
    Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn't a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven...

Incredible Demos

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!