Filtering and Sanitizing

Sanitizing user input is a critical part of software development. Trusting or neglecting to sanitize user input could lead to unauthorized access to the content of your application, mainly user data, or even the server your application is hosted on.

Filters - 图1

Full image on XKCD

The Phalcon\Filter component provides a set of commonly used filters and data sanitizing helpers. It provides object-oriented wrappers around the PHP filter extension.

Types of Built-in Filters

The following are the built-in filters provided by this component:

NameDescription
absintCasts the value as an integer and returns the absolute value of it.
alphanumRemove all characters except [a-zA-Z0-9]
emailRemove all characters except letters, digits and !#$%&*+-/=?^_{|}[email protected][]`.
floatRemove all characters except digits, dot, plus and minus sign.
float!Remove all characters except digits, dot, plus and minus sign and cast the result as a float.
intRemove all characters except digits, plus and minus sign.
int!Remove all characters except digits, plus and minus sign and cast the result as an integer.
lowerApplies the strtolower function
stringStrip tags and encode HTML entities, including single and double quotes.
striptagsApplies the strip_tags function
trimApplies the trim function
upperApplies the strtoupper function

Please note that the component uses the filter_var PHP function internally.

Constants are available and can be used to define the type of filtering required:

  1. <?php
  2. const FILTER_ABSINT = "absint";
  3. const FILTER_ALPHANUM = "alphanum";
  4. const FILTER_EMAIL = "email";
  5. const FILTER_FLOAT = "float";
  6. const FILTER_FLOAT_CAST = "float!";
  7. const FILTER_INT = "int";
  8. const FILTER_INT_CAST = "int!";
  9. const FILTER_LOWER = "lower";
  10. const FILTER_STRING = "string";
  11. const FILTER_STRIPTAGS = "striptags";
  12. const FILTER_TRIM = "trim";
  13. const FILTER_UPPER = "upper";

Sanitizing data

Sanitizing is the process which removes specific characters from a value, that are not required or desired by the user or application. By sanitizing input we ensure that application integrity will be intact.

  1. <?php
  2. use Phalcon\Filter;
  3. $filter = new Filter();
  4. // Returns '[email protected]'
  5. $filter->sanitize('some(one)@exa\mple.com', 'email');
  6. // Returns 'hello'
  7. $filter->sanitize('hello<<', 'string');
  8. // Returns '100019'
  9. $filter->sanitize('!100a019', 'int');
  10. // Returns '100019.01'
  11. $filter->sanitize('!100a019.01a', 'float');

Sanitizing from Controllers

You can access a Phalcon\Filter object from your controllers when accessing GET or POST input data (through the request object). The first parameter is the name of the variable to be obtained; the second is the filter to be applied on it.

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class ProductsController extends Controller
  4. {
  5. public function indexAction()
  6. {
  7. }
  8. public function saveAction()
  9. {
  10. // Sanitizing price from input
  11. $price = $this->request->getPost('price', 'double');
  12. // Sanitizing email from input
  13. $email = $this->request->getPost('customerEmail', 'email');
  14. }
  15. }

Filtering Action Parameters

The next example shows you how to sanitize the action parameters within a controller action:

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class ProductsController extends Controller
  4. {
  5. public function indexAction()
  6. {
  7. }
  8. public function showAction($productId)
  9. {
  10. $productId = $this->filter->sanitize($productId, 'int');
  11. }
  12. }

Filtering data

In addition to sanitizing, Phalcon\Filter also provides filtering by removing or modifying input data to the format we expect.

  1. <?php
  2. use Phalcon\Filter;
  3. $filter = new Filter();
  4. // Returns 'Hello'
  5. $filter->sanitize('<h1>Hello</h1>', 'striptags');
  6. // Returns 'Hello'
  7. $filter->sanitize(' Hello ', 'trim');

Combining Filters

You can also run multiple filters on a string at the same time by passing an array of filter identifiers as the second parameter:

  1. <?php
  2. use Phalcon\Filter;
  3. $filter = new Filter();
  4. // Returns 'Hello'
  5. $filter->sanitize(
  6. ' <h1> Hello </h1> ',
  7. [
  8. 'striptags',
  9. 'trim',
  10. ]
  11. );

Adding filters

You can add your own filters to Phalcon\Filter. The filter function could be an anonymous function:

  1. <?php
  2. use Phalcon\Filter;
  3. $filter = new Filter();
  4. // Using an anonymous function
  5. $filter->add(
  6. 'md5',
  7. function ($value) {
  8. return preg_replace('/[^0-9a-f]/', '', $value);
  9. }
  10. );
  11. // Sanitize with the 'md5' filter
  12. $filtered = $filter->sanitize($possibleMd5, 'md5');

Or, if you prefer, you can implement the filter in a class:

  1. <?php
  2. use Phalcon\Filter;
  3. class IPv4Filter
  4. {
  5. public function filter($value)
  6. {
  7. return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
  8. }
  9. }
  10. $filter = new Filter();
  11. // Using an object
  12. $filter->add(
  13. 'ipv4',
  14. new IPv4Filter()
  15. );
  16. // Sanitize with the 'ipv4' filter
  17. $filteredIp = $filter->sanitize('127.0.0.1', 'ipv4');

Complex Sanitizing and Filtering

PHP itself provides an excellent filter extension you can use. Check out its documentation: Data Filtering at PHP Documentation

Implementing your own Filter

The Phalcon\FilterInterface interface must be implemented to create your own filtering service replacing the one provided by Phalcon.