Filter

Phalcon Filters

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.

Sanitizing content can be achieved using the Phalcon\Filter and Phalcon\Filter\FilterFactory classes.

Configurations

You can add your own filters into the PHP Configuration file.

.env
# define your own service provider
PROVIDER_COOKIES=\Zemit\Provider\Filter\ServiceProvider
./app/config/config.php

'filters' => [
    Filter::FILTER_MD5 => Filters\Md5::class,
    Filter::FILTER_JSON => Filters\Json::class,
    Filter::FILTER_IPV4 => Filters\IPv4::class,
    Filter::FILTER_IPV6 => Filters\IPv6::class,
    
    // You can add your own custom filters
    'my-custom-filter' => App\Filters\Custom::class,
],

Filters

<?php

// Phalcon Native Filters
const FILTER_ABSINT      = 'absint';
const FILTER_ALNUM       = 'alnum';
const FILTER_ALPHA       = 'alpha';
const FILTER_BOOL        = 'bool';
const FILTER_EMAIL       = 'email';
const FILTER_FLOAT       = 'float';
const FILTER_INT         = 'int';
const FILTER_LOWER       = 'lower';
const FILTER_LOWERFIRST  = 'lowerFirst';
const FILTER_REGEX       = 'regex';
const FILTER_REMOVE      = 'remove';
const FILTER_REPLACE     = 'replace';
const FILTER_SPECIAL     = 'special';
const FILTER_SPECIALFULL = 'specialFull';
const FILTER_STRING      = 'string';
const FILTER_STRIPTAGS   = 'striptags';
const FILTER_TRIM        = 'trim';
const FILTER_UPPER       = 'upper';
const FILTER_UPPERFIRST  = 'upperFirst';
const FILTER_UPPERWORDS  = 'upperWords';
const FILTER_URL         = 'url';

// Zemit Filters
const FILTER_MD5         = 'md5';
const FILTER_JSON        = 'json';
const FILTER_IPV4        = 'ipv4';
const FILTER_IPV6        = 'ipv6';

Usage

// examples using custom filters
$this->filter->sanitize($md5, Filter::FILTER_MD5);
$this->filter->sanitize($json, Filter::FILTER_JSON);
$this->filter->sanitize($ipv4, Filter::FILTER_IPV4);
$this->filter->sanitize($ipv5, Filter::FILTER_IPV6);

// using your own custom filter
$this->filter->sanitize($custom, 'my-custom-filter');

// if the class is aware of injections
$filter = $this->filter;

// if the container is present
$filter = $this->di->get('filter');

// from outside
$filter = Di::getDefault()->get('filter');

API References

Phalcon\Filter

Zemit\Filter

Sources

Last updated