Data Filtering
Time to leave $_GET and $_POST in the dust! In fact, you probably shouldn’t use $_GET and $_POST anymore. Since PHP 5.2, there is a new and better way to safely retrieve user-submitted data.
How many times have we heard about security issues in PHP applications stemming from unescaped GET and POST parameters? Proper escaping of input is a perennial problem with web development in general.
On the database side, many worries over SQL injection have been squelched. The clever developers of PDO have constructed a library that analyzes data and escapes it appropriately. The problem of validating and sanitizing input is still a substantial issue on the front-end. Many PHP developers still spend time on development cycles building custom code to filter input or use a framework just for the validation helpers.
PHP (5.2 onward) has a built-in filtering system that makes the tasks of validating and sanitizing data easy. Rather than accessing the $_GET and $_POST superglobals directly, you can make use of PHP functions like filter_input() and filter_input_array().
$theGetVar = filter_input(INPUT_GET, ‘someGetVar’, FILTER_SANITIZE_STRING); // Same as doing the below and running it through a validator $theGetVar = $_GET['someGetVar'];
Using post is also as easy, just change “INPUT_GET” to “INPUT_POST”
Are you sick of writing your own regex for validating an email address, url or even an IP?
// Email $email = filter_input(INPUT_GET, ‘Email’, FILTER_VALIDATE_EMAIL); // URL $url = filter_input(INPUT_GET, ‘URL’, FILTER_VALIDATE_URL); // IP $ip = filter_input(INPUT_GET, ‘URL’, FILTER_VALIDATE_IP);
You can use multiple filters on one input:
$email = filter_input(INPUT_GET, ‘Email’, FILTER_VALIDATE_EMAIL| FILTER_SANITIZE_EMAIL);
Filters won’t solve every security-related problem, but it’s a great step in the right direction when it comes to writing safe code. Below are the php.net docs:


