PHP Data Sanitization w/ Filter

PHP is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded easily into HTML. PHP is particularly well designed for dynamic Web applications, server-side scripting and database interaction. However the ease of accessing data stores and presenting dynamic information to users can lead to serious security risks when user input is involved.

Data sanitizing is a simple means of taking any data inputted by a user and filtering out any content your application is not expecting (and you want to avoid!). Never trust the data a user may input will be accurate and harmless. PHP 5.2.0 is packaged with the filter() functions that provide basic filtering of specific types of data based on function arguments:

<?php
$myIPaddress = "10.10.141.3";
if (filter_var($ip, FILTER_VALIDATE_IP)){
     echo $myIPaddress." is a valid IP address";
} else {
     echo $myIPaddress." is not a valid IP address";
}
?>

This basic function performs a check against the variable $myIPaddress to ensure it is a valid IP address. Performing these function checks against user-inputted data via the $_GET or $_POST global arrays is an absolute necessity for any user input field in an application. The filter functions provide standard data filtering saving the time and effort of creating custom functions to filter data.

There are many variations of these functions to check various types of data. Visit http://www.w3schools.com/PHP/filter_validate_ip.asp for more information on specific syntax.

3 Responses to “PHP Data Sanitization w/ Filter”

  1. Marcus Del Greco says:

    Henninger’s got a post in the works about client-side validation. We’ve got this one covered…

  2. Ed Sawyer says:

    Client-side validation is usually via javascript, which while useful from a functional standpoint, is pretty easily defeated from a security point of view.

    It’s nice PHP has built-in validators for this stuff now. Even if the data is valid however, still often need to check if permissions should allow it. Thinking of url-hacking type attacks here (e.g. passing an integer on the URL, and having the user change it to a different integer for example).

    On the ColdFusion side of things we see a lot of SQL-injection based attacks via the FORM / POST variable scopes, so parameterizing query variables (like those passed on the URL) is crucial in any language (like PHP or CF).

    I think at WebSolutions we’ll be doing more PHP-based stuff in the future (blogs/content management/etc.)

    -Ed

  3. [...] disabled or that someone with malicious intent might try to circumvent the validation. Check out Toby’s article on PHP’s filter function for an example of server side data [...]

Leave a Reply

Panorama theme by Themocracy