Never having to use $_GET or $_POST again

I completely missed this great new feature build in PHP 5.2 since I haven’t been using much vanilla PHP lately due to my preference for CodeIgniter.

CodeIgniter offers great input validation by just using the following code.

$something = $this->input->post('something');
$somethingelse = $this->input->get('something');

But with the release of version 5.2 PHP now offers a great data-sanitizing function right out-of-the-box.

$my_string = filter_input(INPUT_GET, ‘my_string’, FILTER_SANITIZE_STRING);

The code above essentially gets $_GET[‘my_string’] and makes sure it is stripped of any HTML, SQL or other harmful code. If you don’t want to filter you’re variables you can still use the following code.

$my_string = filter_input(INPUT_GET, ‘my_string’, FILTER_UNSAFE_RAW);

This doesn’t just work for $_GET and $_POST but also for $_SERVER and $_COOKIE variables. Check out the documentation for filter_input() on the PHP website. You might also want to have a look at the functions filter_var(), filter_input_array() and filter_var_array() since they offer the same sanitation of data for arrays and non-external variables.

7 Replies to “Never having to use $_GET or $_POST again”

  1. This API is cumbersome. Nobody’s using it.

    I’ve migrated to object-structured OO wrappers for the input arrays. It’s simpler to write $_REQUEST->name(“var”) than remembering FILTER_-constants. And unlike the wacky filter() API it cannot be circumvented, it’s centralized and thus can have built-in logging and reporting.

    1. That’s true, like I said I’ve been using CodeIgniter which sanitizes and filters values right out of the box.

      The fact they brought this to vanilla PHP clearly shows they want to make PHP more secure. Sadly I don’t think it’ll be widely adopted by the developers!

  2. I agree that it is long time over do to be brought into the base PHP and like most I have been using the frameworks that sanitize automagically. It should be brought to the fore-front and talked about more openly and why it is not is a good question. Thank you for posting this, Luc!

  3. I already had hooks for this in my MVC framework as well, and simply added the new filter API. It’s been working very nicely.

    Adoption of request parameter filtering and validation is a problem for most developers, regardless of primary language. I can tell you from my day job that Java developers aren’t doing a great job of filtering input either.

Comments are closed.