A PHP fluent input sanitiser.
Philter accepts untrusted input, passes it through some filters and returns it back to you. It is not a substitution for validation.
Installation
Copy the src/Philter.php
file to your project, or install using composer:
composer require indgy/philter
Getting started
Create a new Philter instance passing in the untrusted input, then combine filters for the untrusted input to pass through and finally call toBool()
, toFloat()
, toInt()
or toString()
to get the filtered and now trusted input.
use \Indgy\Philter;
$f = new Philter($unsafe_input);
$str = $f->in(['safe','string','options'])
->default('safe')
->toString();
There is also a handy shortcut function to return a new Philter instance:
use function \Indgy\philter;
$str = philter($unsafe_input)
->in(['safe', 'string', 'options'])
->default('safe')
->toString();
Available filters
allow(String $chars)
- Allow only the characters in \$chars
alpha()
- Allow only a-z
alphanum()
- Allow only a-z and 0-9
ascii()
- Allow only ASCII chars (32-127), transliterating where possible
between(Int $min, Int $max)
- Allow values between min and max inclusive
contains(String $match)
- Allow values containing \$match
cut(Int $length)
- Cut string to \$length
digits()
- Allow only 0-9
in(Array $items)
- Allow if in \$items
max(Int $max)
- Allow only if less than or equal to \$max
min(Int $min)
- Allow only if greater than or equal to \$min
numeric()
- Allow only if numeric, e.g. currency string
trim()
- Trim characters from beginning and end (see also ltrim()
and rtrim()
)
utf8()
- Convert to UTF-8 transliterating where possible
Refer to the Reference for more detail on the filters.
Custom filters
Define custom filters using the apply()
method with a closure. The closure will be passed the current input value and expects it, or null to be returned.
philter('Here we go.. ')->apply(function($v) {
// always skip filtering if $value is null
if (is_null($v)) return $v;
// do your thing here
$v = $v.= 'I was philtered';
// always return $v or null if it does not pass your filter criteria
return $v;
})->toString();
Documentation
Refer to the user guide or browse the API .