-
Notifications
You must be signed in to change notification settings - Fork 0
Sanitizing and Validation
This class contains functionality for validating and sanitizing various types of data such as email addresses, credit card numbers, phone numbers, etc.
All functions in this class are available in both by-value and by-reference versions.
Use:
\blobfolio\common\sanitize (by value)
\blobfolio\common\ref\sanitize (by reference)
Remove accents from characters in a string.
| Type | Description | Notes |
|---|---|---|
string, array
|
String. | If an array is passed, each value will be processed recursively. |
Returns the unaccented string if passing by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::accents('Björk Guðmundsdóttir is a swan.'); // Bjork Gudmundsdottir is a swan.
// By reference.
\blobfolio\common\ref\sanitize::accents($foo);Decode entities, remove control characters, and trim edge whitespace.
Please note: this function is not for safely inserting a string value into HTML. For that, use ::html().
| Type | Description | Notes |
|---|---|---|
string, array
|
String. | If an array is passed, each value will be processed recursively. |
Returns the sanitized string if passing by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::attribute_value(' Björk"" '); // Bjork""
// By reference.
\blobfolio\common\ref\sanitize::attribute_value($foo);Sanitize an Australian state's 2/3-digit abbreviation. If the full name of a state or territory is passed, the abbreviation is returned.
| Type | Description | Notes |
|---|---|---|
string, array
|
State/Territory. | If an array is passed, each value will be processed recursively. |
Returns a valid 2/3-digit abbreviation or "" by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::au_state('new south wales'); // NSW
$foo = \blobfolio\common\sanitize::au_state('QLD'); // QLD
// By reference.
\blobfolio\common\ref\sanitize::au_state($foo);Validate a credit card number, short of going so far as to check with the bank.
| Type | Description |
|---|---|
string |
Card number. |
By value, returns the card number if valid, otherwise FALSE. By reference returns TRUE or FALSE.
if (false === \blobfolio\common\sanitize::cc($ccnum)) {
throw new Exception('A valid credit card number is required.');
}Removes control characters from a string, including "\0".
| Type | Description | Notes |
|---|---|---|
string, array
|
String. | If an array is passed, each value will be processed recursively. |
Returns the sanitized string if passing by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::control_characters('\0hi'); // hi
// By reference.
\blobfolio\common\ref\sanitize::control_characters($foo);Validate an ISO country code. If a full country name is passed, it will be converted back to an ISO code.
| Type | Description | Notes |
|---|---|---|
string, array
|
Country. | If an array is passed, each value will be processed recursively. |
Returns a valid ISO code or "" by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::country('US'); // US
$foo = \blobfolio\common\sanitize::country('canada'); // CA
// By reference.
\blobfolio\common\ref\sanitize::country($foo);Sanitize a cell for insertion into a CSV. This escapes quotation marks and strips new lines.
| Type | Description | Notes |
|---|---|---|
string, array
|
String. | If an array is passed, each value will be processed recursively. |
Returns the sanitized string by value, otherwise TRUE.
// By value.
$Row = array(
'John',
'"The Man"',
'Doe'
);
$Row = \blobfolio\common\sanitize::csv($Row);
/*
array(
John
""The Man""
Doe
)
*/
// By reference.
\blobfolio\common\ref\sanitize::csv($Row);Format a date string or timestamp in YYYY-MM-DD format.
| Type | Description | Notes |
|---|---|---|
string, array
|
Date. | If an array is passed, each value will be processed recursively. |
Returns the date or "0000-00-00" by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::date('2015-01-01 11:23:48'); // 2015-01-01
$foo = \blobfolio\common\sanitize::date(1485211108); // 2017-01-23
// By reference.
\blobfolio\common\ref\sanitize::date($foo);Format a datetime string or timestamp in YYYY-MM-DD HH:MM:SS format.
| Type | Description | Notes |
|---|---|---|
string, array
|
Date. | If an array is passed, each value will be processed recursively. |
Returns the date or "0000-00-00 00:00:00" by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::datetime('2015-01-01 11:23:48'); // 2015-01-01 11:23:48
$foo = \blobfolio\common\sanitize::datetime(1485211108); // 2017-01-23 14:38:28
// By reference.
\blobfolio\common\ref\sanitize::datetime($foo);Sanitize a domain name. This function will tease out the FQDN portion of an arbitrary string, strip leading www. subdomains, convert Unicode to ASCII*, and validate the suffix.
Note: with this function, IP addresses and non-FQDN results will be returned as an empty string.
| Type | Description | Notes | Default |
|---|---|---|---|
string, array
|
Domain, URL, etc. | If an array is passed, each value will be processed recursively. | |
bool |
Return Unicode. | If TRUE and the domain is Unicode, it will be returned thusly rather than being converted to ASCII. |
FALSE |
Returns the domain name or "" by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::domain('http://apple.com'); // apple.com
//by ref
\blobfolio\common\ref\sanitize::domain($foo);Validate/sanitize an EAN-13. This should work with EAN-8 as well, but will zero-pad the results.
| Type | Description | Notes | Default |
|---|---|---|---|
string, array
|
EAN. | If an array is passed, each value will be processed recursively. | |
bool |
Hyphenate output. | FALSE |
Returns the EAN or "" by value, otherwise TRUE/FALSE.
// By value.
$foo = \blobfolio\common\sanitize::ean('0709077260149', true); // 0-709077-260149
// By reference.
\blobfolio\common\ref\sanitize::ean($foo);Sanitize an email address. This will remove invalid characters, quotes and apostrophes, convert to lowercase, and ensure that the host is a FQDN.
This is a little more restrictive than the pure spec and PHP's native FILTER_SANITIZE_EMAIL. Local parts (the user) can contain A-Z, 0-9, and the following special characters: . ! # $ % & * + - = ? _ ~. Anything else, including comments like user(blabla)@foo.com, will be stripped, but won't otherwise cause a validation failure.
Unicode/IDN hosts are A-OK if the PHP extension intl is installed, but will be converted to Punycode/ASCII format.
IP addresses and hosts with invalid suffix structures will be considered invalid.
| Type | Description | Notes |
|---|---|---|
string, array
|
Email. | If an array is passed, each value will be processed recursively. |
Returns a valid email address or "" by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::email('jane@localhost'); // [empty string]
$foo = \blobfolio\common\sanitize::email('Jane@Doe.com'); // jane@doe.com
// By reference.
\blobfolio\common\ref\sanitize::email($foo);Sanitize a file extension. This converts the extension to lowercase and removes leading "*" and ".". Note: this will not attempt to parse paths; this is meant only to be run against an already-extracted extension.
| Type | Description | Notes |
|---|---|---|
string, array
|
Extension. | If an array is passed, each value will be processed recursively. |
Returns the file extension.
// By value.
$foo = \blobfolio\common\sanitize::file_extension('.JPG'); // jpg
// By reference.
\blobfolio\common\ref\sanitize::file_extension($foo);Escape UTF-8 HTML. Note: this should only be run once on a given block of text or else entities might be double-encoded.
| Type | Description | Notes |
|---|---|---|
string, array
|
HTML. | If an array is passed, each value will be processed recursively. |
Returns the HTML by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::html('<b>Hello</b>'); //<b>Hello</b>
// By reference.
\blobfolio\common\ref\sanitize::html($foo);Try to tease a hostname from a URL-like string. This will standardize IPs, validate suffixes, handle Unicode, etc.
Unlike ::domain(), the result does not need to be a FQDN.
| Type | Description | Notes | Default |
|---|---|---|---|
string |
String. | ||
bool |
Keep "www."
|
If FALSE, leading "www." subdomains will be stripped. |
FALSE |
bool |
Return Unicode. | If TRUE and the domain is Unicode, it will be returned thusly rather than being converted to ASCII. |
FALSE |
Returns the hostname or FALSE by value, otherwise TRUE/FALSE.
// By value.
$foo = \blobfolio\common\sanitize::hostname('http://www.apple.com', true); // apple.com
//by ref
\blobfolio\common\ref\sanitize::hostname($foo, true);Compact and range-check an IPv4 or IPv6 address.
| Type | Description | Notes | Default |
|---|---|---|---|
string, array
|
IP address. | If an array is passed, each value will be processed recursively. | |
bool |
Allow reserved. | If TRUE, reserved/restricted IPs will be allowed. |
FALSE |
bool |
Compact IPv6 | If TRUE, IPv6 addresses will be returned in compacted notation, otherwise they'll be fully expanded. |
TRUE |
Returns the sanitized IP address or "" by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::ip('2600:3C00::F03C:91FF:FEAE:0FF2'); // 2600:3c00::f03c:91ff:feae:ff2
// By reference.
\blobfolio\common\ref\sanitize::ip($foo);Sanitizes an IRI value to ensure it is well-formed and matches the allowed protocols and domains. By default it is designed for SVG values, but the whitelists can be augmented.
| Type | Description | Notes | Default |
|---|---|---|---|
string, array
|
String. | If an array is passed, each value will be processed recursively. | |
array |
Allowed protocols. | The protocols, if any, will be combined with the default. | ["http", "https"] |
array |
Allowed domains. | The domains, if any, will be combined with the default. | ["creativecommons.org", "inkscape.org", "sodipodi.sourceforge.net", "w3.org"] |
Returns the sanitized string if passing by value, otherwise TRUE. Invalid values will be returned/set as an empty string.
// By value.
$foo = \blobfolio\common\sanitize::iri_value('javascript: alert(Hi);'); // [empty string]
// By reference.
\blobfolio\common\ref\sanitize::iri_value($foo);Validate/sanitize an ISBN-10 or ISBN-13 code.
| Type | Description | Notes |
|---|---|---|
string, array
|
ISBN. | If an array is passed, each value will be processed recursively. |
Returns the ISBN or "" by value, otherwise TRUE/FALSE. Note: this will strip hyphenation.
// By value.
$foo = \blobfolio\common\sanitize::isbn('0939117606'); // 0939117606
// By reference.
\blobfolio\common\ref\sanitize::isbn($foo);Escape a variable for insertion into a Javascript string. This removes newlines, straightens quotes, and escapes the enclosing quote.
| Type | Description | Notes | Default |
|---|---|---|---|
string, array
|
String. | If an array is passed, each value will be processed recursively. | |
string |
Quote type. | Either " or '. |
' |
Returns the sanitized string by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::js("How's it going?", "'"); // How\'s it going?
// By reference.
\blobfolio\common\ref\sanitize::js($foo);Sanitize a MIME type.
| Type | Description | Notes |
|---|---|---|
string, array
|
MIME type. | If an array is passed, each value will be processed recursively. |
Returns the MIME type by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::mime('Application/Octet-Stream'); // application/octet-stream
// By reference.
\blobfolio\common\ref\sanitize::mime($foo);Try to sanitize a person's name. This is a fool's errand, but tries to strip out completely unreasonable data.
| Type | Description | Notes |
|---|---|---|
string, array
|
Name. | If an array is passed, each value will be processed recursively. |
Returns the sanitized name by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::name("Henry!!\nThe great"); // Henry The Great
// By reference.
\blobfolio\common\ref\sanitize::name($foo);This is also a bit of a fool's errand, but exists mainly to prevent simple user errors (like extra whitespace) or system conflicts due to crazy input. It essentially combines the whitespace() and printable() filters.
This sort of filter needs to be implemented at the beginning of a project, otherwise you run the risk of preventing users from being able to type their original passwords.
| Type | Description | Notes |
|---|---|---|
string, array
|
Password. | If an array is passed, each value will be processed recursively. |
Returns the password by value, otherwise TRUE.
This strips out everything other than tabs, spaces, newlines, and characters that "use ink". Note: the behaviors may vary by environment, so be sure to test before implementing.
| Type | Description | Notes |
|---|---|---|
string, array
|
String. | If an array is passed, each value will be processed recursively. |
Returns the printable string by value, otherwise TRUE.
Sanitize a Canadian province's 2-digit abbreviation. If the full name of a province or territory is passed, the abbreviation is returned.
| Type | Description | Notes |
|---|---|---|
string, array
|
Province. | If an array is passed, each value will be processed recursively. |
Returns a valid 2-digit abbreviation or "" by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::province('alberta'); // AB
$foo = \blobfolio\common\sanitize::province('ON'); // ON
// By reference.
\blobfolio\common\ref\sanitize::province($foo);Straighten those awful curly quotes and apostrophes!
| Type | Description | Notes |
|---|---|---|
string, array
|
String. | If an array is passed, each value will be processed recursively. |
Returns the string with normal quotes by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::quotes('“T’was the night before Christmas...”'); // "T'was the night before Christmas..."
// By reference.
\blobfolio\common\ref\sanitize::quotes($foo);Sanitize a US state's 2-digit abbreviation. If the full name of a state or territory is passed, the abbreviation is returned.
| Type | Description | Notes |
|---|---|---|
string, array
|
State/Territory. | If an array is passed, each value will be processed recursively. |
Returns a valid 2-digit abbreviation or "" by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::state('puerto rico'); // PR
$foo = \blobfolio\common\sanitize::state('TX'); // TX
// By reference.
\blobfolio\common\ref\sanitize::state($foo);Sanitize a block of SVG code for e.g. insertion into a web page. This function is called by image::clean_svg() when the "sanitize" argument is TRUE. If the more advanced handling of image::clean_svg() isn't needed, this can be called on its own.
The following sanitizing methods are employed:
- Removal of comments (
<!-- -->and/* */varieties); - Removal of XML, PHP, ASP;
- Removal of Javascript tags, attributes, and values;
- Sanitizing of CSS
url(...)rules; - Namespace and IRI sanitizing via protocol and host (both extensible);
- Extensible tag whitelist;
- Extensible attribute whitelist;
- Miscellaneous formatting repairs;
- Whitespace collapsing;
| Type | Description | Default |
|---|---|---|
string, array
|
SVG code. | |
array |
Additional whitelisted tags. | NULL |
array |
Additional whitelisted attributes. | NULL |
array |
Additional whitelisted protocols. | NULL |
array |
Additional whitelisted domains. | NULL |
Returns sanitized SVG code or an empty string on failure by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::svg('<svg ... />');
// By reference.
\blobfolio\common\ref\sanitize::svg($foo);Sanitize a timezone string. If not found among PHP's master list, it defaults to "UTC".
| Type | Description | Notes |
|---|---|---|
string, array
|
Timezone. | If an array is passed, each value will be processed recursively. |
Returns a valid timezone string or "UTC" by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::timezone('foobar'); // UTC
$foo = \blobfolio\common\sanitize::timezone('america/chicago'); // America/Chicago
// By reference.
\blobfolio\common\ref\sanitize::timezone($foo);Ensure a value falls between a minimum and/or maximum boundary.
| Type | Description | Notes | Default |
|---|---|---|---|
mixed, array
|
Value. | If an array is passed, each value will be processed recursively. | |
mixed |
Minimum value. | If NULL, no minimum is checked. |
NULL |
mixed |
Maximum value. | If NULL, no maximum is checked. |
NULL |
If a minimum bound is specified and the value is below it, the minimum is returned. Equal and opposite for the maximum. Otherwise the original value is returned. When passing by reference, TRUE is always returned.
// By value.
$foo = \blobfolio\common\sanitize::to_range(5, 1, 10); // 5
$foo = \blobfolio\common\sanitize::to_range('2015-01-01', '2015-02-01'); // 2015-02-01
// By reference.
\blobfolio\common\ref\sanitize::to_range($foo, $min, $max);Remove inappropriate characters from a URL and make sure a valid scheme is present.
| Type | Description | Notes |
|---|---|---|
string, array
|
URL. | If an array is passed, each value will be processed recursively. |
Returns the sanitized URL or "" by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::url('//fonts.google.com'); // https://fonts.google.com
// By reference.
\blobfolio\common\ref\sanitize::url($foo);Validate/sanitize a UPC code.
| Type | Description | Notes | Default |
|---|---|---|---|
string, array
|
UPC. | If an array is passed, each value will be processed recursively. | |
bool |
Hyphenate output. | FALSE |
Returns the UPC or "" by value, otherwise TRUE/FALSE.
// By value.
$foo = \blobfolio\common\sanitize::upc('089218545992', true); // 0-89218-54599-2
// By reference.
\blobfolio\common\ref\sanitize::upc($foo);Ensure the string is encoded as UTF-8, convert if necessary, and strip invalid UTF garbage. Numeric and boolean values are left unaltered.
| Type | Description | Notes |
|---|---|---|
string, array
|
String. | If an array is passed, each value will be processed recursively. |
Returns a valid UTF-8 string or "" by value, otherwise TRUE.
Trim, collapse horizontal whitespace to a single " ", convert vertical whitespace to "\n", and collapse vertical whitespace to the specified number allowed.
| Type | Description | Notes | Default |
|---|---|---|---|
string, array
|
String. | If an array is passed, each value will be processed recursively. | |
int |
Newlines. | If 0, vertical whitespace will be converted to horizontal whitespace and collapsed, otherwise contiguous vertical whitespace in excess of this value will be removed. |
0 |
Returns the sanitized string by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::whitespace('Happy Birthday'); // Happy Birthday
// By reference.
\blobfolio\common\ref\sanitize::whitespace($foo);An alias of whitespace() with a default $newlines value of 1.
Ensure a 5-digit ZIP string by chopping off +4 or zero-padding short entries.
Note: this does not validate the particular combination of digits.
| Type | Description | Notes |
|---|---|---|
string, array
|
ZIP. | If an array is passed, each value will be processed recursively. |
Returns a 5-digit ZIP Code or "" by value, otherwise TRUE.
// By value.
$foo = \blobfolio\common\sanitize::zip5('12345+6789'); // 12345
// By reference.
\blobfolio\common\ref\sanitize::zip5($foo);CLI
Constants
Dom Helpers
- ::get_nodes_by_class()
- ::innerhtml()
- ::load_svg()
- ::parse_css()
- ::remove_namespace()
- ::remove_node()
- ::remove_nodes()
- ::save_svg()
Files and Paths
- ::copy()
- ::csv_headers()
- ::data_uri()
- ::dirsize()
- ::empty_dir()
- ::hash_dir()
- ::leadingslash()
- ::line_count()
- ::mkdir()
- ::path()
- ::readfile_chunked()
- ::redirect()
- ::rmdir()
- ::scandir()
- ::trailingslash()
- ::unixslash()
- ::unleadingslash()
- ::unparse_url()
- ::untrailingslash()
Formatting
- ::array_flatten()
- ::array_to_indexed()
- ::ceil()
- ::cidr_to_range()
- ::decode_entities()
- ::decode_escape_entities()
- ::decode_js_entities()
- ::decode_unicode_entities()
- ::excerpt()
- ::floor()
- ::fraction()
- ::inflect()
- ::ip_to_number()
- ::ip_to_subnet()
- ::json()
- ::json_decode()
- ::json_encode()
- ::links()
- ::list_to_array()
- ::money()
- ::number_to_ip()
- ::phone()
- ::round()
- ::to_csv()
- ::to_timezone()
- ::to_xls()
General Data Helpers
- ::array_compare()
- ::array_idiff()
- ::array_iintersect()
- ::array_ikey_exists()
- ::array_isearch()
- ::array_map_recursive()
- ::array_otherize()
- ::array_pop()
- ::array_pop_rand()
- ::array_pop_top()
- ::cc_exp_months()
- ::cc_exp_years()
- ::datediff()
- ::iin_array()
- ::in_range()
- ::ip_in_range()
- ::is_json()
- ::is_utf8()
- ::json_decode_array()
- ::length_in_range()
- ::parse_args()
- ::random_int()
- ::random_string()
- ::switcheroo()
- ::unsetcookie()
Images
Multi-Byte Wrappers
- ::parse_str()
- ::parse_url()
- ::str_pad()
- ::str_split()
- ::strlen()
- ::strpos()
- ::strrev()
- ::strrpos()
- ::strtolower()
- ::strtoupper()
- ::substr()
- ::substr_count()
- ::trim()
- ::ucfirst()
- ::ucwords()
- ::wordwrap()
Sanitizing and Validation
- ::accents()
- ::attribute_value()
- ::au_state()
- ::ca_postal_code()
- ::cc()
- ::control_characters()
- ::country()
- ::csv()
- ::date()
- ::datetime()
- ::domain()
- ::ean()
- ::email()
- ::file_extension()
- ::html()
- ::hostname()
- ::ip()
- ::iri_value()
- ::isbn()
- ::js()
- ::mime()
- ::name()
- ::password()
- ::printable()
- ::province()
- ::quotes()
- ::state()
- ::svg()
- ::timezone()
- ::to_range()
- ::upc()
- ::url()
- ::utf8()
- ::whitespace()
- ::whitespace_multiline()
- ::zip5()
Typecasting