Posts

Showing posts from June, 2012

Input Validation Using Filter Functions

The filter_input() function was introduced in PHP 5.2.0 and allows you to get an external variable by name and filter it. This is incredibly useful when dealing with $_GET and $_POST data. Let’s take as an example a simple page that reads a value passed in from the URL and handles it. We know this value should be an integer between 15 and 20. One way of doing would be something like: <?php if (isset($_GET["value"])) { $value = $_GET["value"]; } else { $value = false; } if (is_numeric($value) && ($value >= 15 && $value <= 20)) { // run my code } else { // handle the issue } This is a really basic example and already we are writing more lines that I would like to see. First, because we can’t be sure $_GET is set, the code performs an appropriate check so that the script doesn’t fall over. Next is the fact that $value is now a “dirty” variable because it has been directly assigned from a $_GET value. We would need to take