util.php is a collection of useful functions and snippets that you need or could use every day. It's implemented as a class with static methods, to avoid conflicts with your existing code-base. Just drop it in and start using it immediately.

Included are 60+ functions that provide you with the ability to do common tasks much easier and more efficiently, without having to find that one comment on php.net where you know its been done already. Access superglobals without checking to see if certain indexes are set first and pass default values, use a nicely formatted var dump, validate emails, generate random strings, flatten an array, pull a single column out of a multidimensional array and much more.

Although it's implemented as one giant class, util.php has extensive documentation and a full suite of unit tests to avoid breaking backwards-compatibility unintentionally.

The project is hosted on GitHub. You can report bugs and discuss features on the issues page, or send tweets to @brandonwamboldt.

Downloads (Right-click, and use "Save As")

Stable Version (1.1.0)
Unstable Version (master)

Installation

Server Requirements
Standalone File

Simply drop util.php in any project and call include 'util.php'; in your project. You can then access the Util class.

Composer

Add the following dependency to your composer.json:

"brandonwamboldt/utilphp": "1.1.*"
When used with composer, the class is namespaced (\utilphp\util) instead of just util.

Debugging Functions

var_dump util::var_dump(mixed $var[, bool $return = FALSE])

Nicely prints out the contents of a passed variable. Booleans are properly displayed as 'true' or 'false', null values are shown as 'NULL', variable types are displayed, and arrays and objects are displayed as a collapsible tree powered by JavaScript.

Usage:

util::var_dump($var);

Array/Object Functions

array_first util::array_first(array $array)

Retrieve the first value from an array. Can be run on function callbacks, and it will not modify the pointer of the source array unlike most other methods of doing this.

Usage:

util::array_first( ['a', 'b', 'c'] );
=> Returns 'a'

array_first_key util::array_first_key(array $array)

Retrieve the first key from an array. Can be run on function callbacks, and it will not modify the pointer of the source array unlike most other methods of doing this.

Usage:

util::array_first_key( $users );
=> Returns 'brandon'

array_flatten util::array_flatten(array $array[, bool $preserve_keys = TRUE])

Flattens a multi-dimensional array into a one dimensional array

Usage:

util::array_flatten( [ 'a', 'b', [ 'c', 'd', 'e', [ 'f', 'g', [ [ [ [ 'h', 'i', 'j' ] ] ] ] ] ] ] );
=> Returns [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' ]

array_get util::array_get($var[, mixed $default = NULL])

Retrieve a value from an array, or return a given default if the index isn't set

Usage:

util::array_get($_POST['action'], 'index');
=> If $_POST['action'] is set, returns its value, otherwise returns 'index'
util::array_get($_POST['action']['do'], 'index');
=> Returns the value of $_POST['action']['do'] or 'index'

array_last util::array_last(array $array)

Retrieve the last value from an array. Can be run on function callbacks, and it will not modify the pointer of the source array unlike most other methods of doing this.

Usage:

util::array_last( [ 'a', 'b', 'c'] );
=> Returns 'c'

array_last_key util::array_last_key(array $array)

Retrieve the last key from an array. Can be run on function callbacks, and it will not modify the pointer of the source array unlike most other methods of doing this.

Usage:

util::array_last_key( $users );
=> Returns 'zane'

array_map_deep util::array_map_deep(array $array, callable $callback[, bool $on_nonscalar = FALSE])

Returns an array containing all the elements of $array after applying the callback function to each one recursively. Particularly useful for avoiding errors when calling functions that only accept scalar values on an array that could contain nested arrays, such as $_GET or $_POST.

Usage:

util::array_map_deep($_POST, 'htmlentities');
=> Recursively escapes each scalar value in $_POST
util::array_map_deep($_POST, 'htmlentities', TRUE);
=> Recursively escapes each value in $_POST regardless of its type

array_pluck util::array_pluck(array $array, string $field[, bool $preserve_keys, bool $remove_nomatches])

Replaces each value in an array with the specified field of the array or object that used to be the value. Very useful when you have an array of objects or arrays from a database, and you only want one specific field. For example, you want an array of emails from an array of users.

Usage:

util::array_pluck([['val' => 1], ['val' => 2], ['val' => 3]], 'val');
=> Returns [1, 2, 3]
util::array_pluck($users, 'email');
=> Returns an array of email addresses for each user

array_search_deep util::array_search_deep(array $array, mixed $search[, string $field = FALSE])

Allows you to search for a value in an array of arrays or an array of objects, and return the key of the value that matches the search criteria. If $field is unspecified, the entire array/object is searched.

Usage:

util::array_search_deep($_POST, 'delete_post');
=> Might return 'do' if $_POST['do']['action'] = 'delete_post'
util::array_search_deep($users, 'rogue_coder', 'username');
=> Might return 5 if $users[5]->username = 'rogue_coder'

array_clean util::array_clean(array $array)

Remove all null/empty/false values from the given array.

Usage:

util::array_clean( array( 'a', 'b', '', null, false, 0) );
=> Returns array('a', 'b');

URL Functions

add_query_arg util::add_query_arg()

Adds one ore more query args to the query string of the current URL or a given URL

Usage:

util::add_query_arg( 'user', '5', '/admin/users?action=edit' );
=> Returns '/admin/users?action=edit&user=5'
util::add_query_arg( [ 'user' => 5, 'action' => 'edit' ], '/admin/users' );
=> Returns '/admin/users?user=5&action=edit'

get_current_url util::get_current_url()

Returns the current URL with hostname

Usage:

util::get_current_url();
=> Returns 'http://brandonwamboldt.ca/utilphp/'

is_https util::is_https()

Returns true if the current page is being loaded over https, false if it isn't

Usage:

util::is_https();
=> Returns false

http_build_url util::http_build_url([mixed $url[, mixed $parts[, int $flags = HTTP_URL_REPLACE[, array &amo;$new_url]]]])

Pure PHP implementation/polyfill for http_build_url which requires pecl_http to be installed.

Usage:

echo util::http_build_url("http://user@www.example.com/pub/index.php?a=b#files",
    array(
        "scheme" => "ftp",
        "host" => "ftp.example.com",
        "path" => "files/current/",
        "query" => "a=c"
    ),
    HTTP_URL_STRIP_AUTH | HTTP_URL_JOIN_PATH | HTTP_URL_JOIN_QUERY | HTTP_URL_STRIP_FRAGMENT
);

The above example will output:

ftp://ftp.example.com/pub/files/current/?a=c

is_https util::is_https()

Returns true if the current page is being loaded over https, false if it isn't

Usage:

util::is_https();
=> Returns false

remove_query_arg util::remove_query_arg( array|string $query_args[, string $url])

Removes one ore more query args from the query string of the current URL or a given URL

Usage:

util::remove_query_arg( 'action', '/admin/users?action=edit&user=5' );
=> Returns '/admin/users?user=5'
util::remove_query_arg( [ 'user', 'action'], '/admin/users?action=edit&user=5' );
=> Returns '/admin/users'

slugify util::slugify(string $string[, string $separator = "-", bool $css_mode = FALSE])

Generate a string safe for use in URLs from any given string. Converts any accent characters to their equivalent normal characters and converts any other non-alphanumeric characters to dashes, then converts any sequence of two or more dashes to a single dash. This function generates slugs safe for use as URLs, and if you pass TRUE as the second parameter, it will create strings safe for use as CSS classes or IDs.

Usage:

util::slugify('This is a random --string with an Ãccent');
=> Returns 'this-is-a-random-string-with-an-accent'
util::slugify('Another String', '.');
=> Returns 'another.string'

String Functions

htmlentities util::htmlentities(string $string[, bool $preserve_encoded_entities = FALSE])

Executes htmlentities with ENT_QUOTES set by default. However, if you pass TRUE as the second parameter, it will not re-encode entities that are already encoded.

Usage:

util::htmlentities('this string < this string', TRUE);
=> Returns 'this string < this string'

htmlspecialchars util::htmlspecialchars(string $string[, bool $preserve_encoded_entities = FALSE])

Executes htmlspecialchars with ENT_QUOTES set by default. However, if you pass TRUE as the second parameter, it will not re-encode entities that are already encoded.

Usage:

util::htmlspecialchars('this string < this string', TRUE);
=> Returns 'this string < this string'

linkify util::linkify(string $text)

Find's any URLs in the specified text and wraps them with HTML anchor tags

Usage:

util::linkify('this string has a link to http://www.google.com');
=> Returns 'this string has a link to <a href="http://www.google.com/">www.google.com</a>'

match_string util::match_string(string $pattern, string $string[, bool $caseSensitive = true])

Check if a string matches a given pattern. You can use '*' as a wildcard character.

Usage:

util::match_string("test/*", "test/my/test");
=> Returns true
util::match_string("test/", "test/my/test");
=> Returns false

random_string util::random_string(int $length[, bool $human_friendly = TRUE, bool $include_symbols = FALSE, bool $no_duplicate_chars = FALSE])

Generates a random string of the specified length. Human friendly mode will exclude characters that can be confused with other characters, such as 0 (zero) and O (capital o), 1 (one) and l (lowercase L).

Usage:

util::random_string(8);
=> Returns 'a6BiF4UW'

number_to_word util::number_to_word(int|float $number)

Converts a number into its text equivalent. For example, 56 becomes fifty-six.

util::number_to_word(512.5);
=> Returns 'five hundred and twelve point five'

ordinal util::ordinal(int $number)

Returns the ordinal version of a number (appends th, st, nd, rd)

Usage:

util::ordinal(22);
=> Returns '22nd'

remove_accents util::remove_accents(string $string)

Converts all accent characters to their ASCII equivalents

Usage:

util::remove_accents('Àccent');
=> Returns 'Accent'

secure_random_string util::secure_random_string(int $length)

Generate a random string of characters. Will attempt to use a secure source (openssl).

Usage:

util::secure_random_string(16);
=> Returns '5bB1RJH0cQhNjviT'

seems_utf8 util::seems_utf8(string $string)

Checks to see if a given string is UTF-8 encoded/safe

Usage:

util::seems_utf8('This is some random string user input');
=> Returns true

safe_truncate util::safe_truncate(string $string, int $length[, string $append = '...'])

Truncate a string to a specified length without cutting a word off

Usage:

util::safe_truncate('The quick brown fox jumps over the lazy dog', 24);
=> Returns 'The quick brown fox...'

size_format util::size_format(int $bytes[, int $decimals = 0])

Formats an integer as a human friendly size string, such as 4 KiB.

Usage:

util::size_format( 25151251, 2 );
=> Returns '23.99 MiB'

str_to_bool util::str_to_bool(string $string)

Converts a string to boolean, looking for yes/no words like 'yes', 'no', 'true', 'false', 'y', 'n', etc

Usage:

util::str_to_bool('yes');
=> Returns true

zero_pad util::zero_pad(int $number, int $length)

Pads a given number with zeroes on the left

Usage:

util::zero_pad(341, 8);
=> Returns '00000341'

strip_space util::strip_space(string $string)

Strip all withspace from the given string

Usage:

util::strip_space(' The quick brown fox jumps over the lazy dog ');
=> Returns 'Thequickbrownfoxjumpsoverthelazydog'

sanitize_string util::sanitize_string(string $string)

Sanitize a string by performing the following operation :

  • Remove accents
  • Lower the string
  • Remove punctuation characters
  • Strip whitespaces

Usage:

util::sanitize_string(' Benoit! à New-York? j’ai perçu 1 % : Qu’as-tu "gagné" chez M. V. Noël? Dix francs.');
=> Returns 'benoitanewyorkjaipercu1quastugagnechezmvnoeldixfrancs'

Files

full_permissions util::full_permissions(string $file)

Returns the file permissions as a nice string, like -rw-r--r--

Usage:

util::full_permissions('/etc/passwd');
=> Returns '-rw-r--r--'

rmdir util::rmdir(string $dir[, bool $traverseSymlinks = false])

Recursively deletes a directories (including all contents).

Usage:

util::rmdir('/tmp/working/dir');
=> Returns true

Serialization

is_serialized util::is_serialized(mixed $data)

Checks to see if a given variable is a seralized data structure

Usage:

util::is_serialized( 'a:0:{}' );
=> Returns true

maybe_serialize util::maybe_serialize(mixed $data)

Serialize data, if needed to store in plaintext (Arrays or objects)

Usage:

util::maybe_serialize( 5 );
=> Returns 5
util::maybe_serialize( array() );
=> Returns 'a:0:{}'

maybe_unserialize util::maybe_unserialize(mixed $data)

Unserialize data, if it's a serialized string

Usage:

util::maybe_unserialize(5);
=> Returns 5
util::maybe_unserialize("a:0:{}");
=> Returns array()

fix_broken_serialization util::fix_broken_serialization(mixed $data)

Attempt to fix a broken serialization string (e.g. where string offsets are incorrect). Can fix errors that frequently occur with mismatched character sets or higher-than-ASCII characters.

Usage:

util::fix_broken_serialization('a:1:{s:4:"test";s:4:"abc";}');
=> Returns 'a:1:{s:4:"test";s:3:"abc";}'

Other

force_download util::force_download(string $filename, string $content = FALSE)

Transmit headers that force a browser to display the download file dialog. Cross browser compatible. Only fires if headers have not already been sent.

Usage:

util::force_download( 'export.csv', file_get_contents( 'securefile.csv' ) );
=> The user will be prompted to download the file

get_client_ip util::get_client_ip(bool $trust_proxy_headers = FALSE)

Returns the IP address of the client. Only enable $trust_proxy_headers if your server is behind a proxy that sets the HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR headers.

Usage:

util::get_client_ip();
=> Returns '12.123.12.100'

get_gravatar util::get_gravatar(string $email, int $size = 32)

Return the URL to a user's gravatar

Usage:

util::get_gravatar('brandon.wamboldt@gmail.com');
=> Returns 'http://www.gravatar.com/avatar/46679faeb6780ecb1ea57527fdc66eb3?s=32'

human_time_diff util::human_time_diff(int $from, int $to = '', int $as_text = FALSE, string $suffix = ' ago')

Converts a unix timestamp to a relative time string, such as "3 days ago" or "2 weeks ago"

Usage:

util::human_time_diff(time() - 7400);
=> Returns '2 hours ago'
util::human_time_diff(time() - 7400, '', TRUE);
=> Returns 'two hours ago'

nocache_headers util::nocache_headers(mixed $data)

Sets the headers to prevent caching for the different browsers

Different browsers support different nocache headers, so several headers must be sent so that all of them get the point that no caching should occur

Usage:

util::nocache_headers();

utf8_headers util::utf8_headers(mixed $content_type = 'text/html')

Transmit UTF-8 content headers if the headers haven't already been sent

Usage:

util::utf8_headers();

validate_email util::validate_email(string $possible_email)

Validate an email address

Usage:

util::validate_email( 'brandon.wamboldt@gmail.com' );
=> Returns true
util::validate_email( 'not an email' );
=> Returns false

Constants

SECONDS_IN_A_MINUTE util::SECONDS_IN_A_MINUTE

The number of seconds in a minute, useful for making code more verbose

SECONDS_IN_AN_HOUR util::SECONDS_IN_AN_HOUR

The number of seconds in an hour, useful for making code more verbose

SECONDS_IN_A_DAY util::SECONDS_IN_A_DAY

The number of seconds in a day, useful for making code more verbose

SECONDS_IN_A_WEEK util::SECONDS_IN_A_WEEK

The number of seconds in a week (7 days), useful for making code more verbose

SECONDS_IN_A_MONTH util::SECONDS_IN_A_MONTH

The number of seconds in a month (30 days), useful for making code more verbose

SECONDS_IN_A_YEAR util::SECONDS_IN_A_YEAR

The number of seconds in a year (365 days), useful for making code more verbose

Change Log

1.1.0
This release introduces a deprecation notice for slugify(), please update your code.

- Added a cryptographically secure random string function secure_random_string. Thanks to @abhimanyusharma003 via Pull Request #53
- Added limit_characters and limit_words functions. Thanks to @abhimanyusharma003 via Pull Request #55
- Added rmdir method to recursively delete a directory. Thanks to @ARACOOOL via Pull Request #56
- Added set_executable, set_readable, set_writable, directory_size, directory_contents and get_user_dir functions. Thanks to @sergserg via Pull Request #70
- Changed parameter ordering for slugify, $css_mode is now the third argument. For backwards compatibility, the old order will still work but it will generate an E_USER_DEPRECATED warning. Thanks to @abhimanyusharma003 via Pull Request #71
- Added match_string method. Thanks to @abhimanyusharma003 via Pull Request #72
- Renamed internal methods (protected ones) for PSR-2 compliance
- General performance improvements, code quality improvements, and increased unit test coverage (special thanks to @hopeseekr for getting us near 100% coverage)

1.0.7
- Added fix_broken_serialization to fix broken serialized strings (Thanks to @hopeseekr via Pull Request #48)
- Fixed get_current_url appending port 80 or 443 when not needed (Thanks to @scottchiefbaker via Pull Request #49)
- var_dump can now handle recursive data structures without crashing
- var_dump code was minified and cleaned up
- array_flatten was optimized (thanks to @hopeseekr via Pull Request #47)
- remove_accents was completely rewritten and is now ~4x faster

1.0.6
- Added start_with function
- Added ends_with function
- Added str_contains function
- Added str_icontains function
- Added get_file_ext function
- Fixing permissions on the files & directories
- Fixing a bug with the include path of util.php

1.0.5
- Issue #29 Fixed error in var_dump if mbstring extension wasn't present
- Adding Composer support
- Updating license from GPL to MIT
- Adding Changelog to project
- Bumping minimum version to PHP 5.3.3

1.0.4
- Issue #22 Removed all superglobal *_get functions, you can use the modified array_get now
- Issue #22 Modifed the behaviour of array_get, see documentation
- Pull Request #21 Added multibyte support to html* functions
- Issue #9 Removed the str_to_utf8 function
- Issue #3 Removed the absint function
- Removed declare() from util.php to avoid errors
- Updated PHPUnit tests to use PHPUnit 3.6

1.0.3
- Issue #16 Improved performance of slugify
- Issue #14 Modified the regex for seems_utf8 to be more accurate
- Issue #13 Changed validate_email to be wrapper for filter_var
- Added 'ok' to the list of yes words for str_to_bool
- str_to_bool matches no followed by any number of 'o's

1.0.2
- Issue #12 get_current_url now includes the port and user/password if required
- Issue #11 human_time_diff now uses the DateTime functions
- Issue #10 is_https no longer checks the port as well

1.0.1
- Issue #7 Added the $trust_proxy_headers parameter to get_client_ip
- Issue #6 Removed is_isset as the function did not work as intended
- Issue #6 Removed is_empty as it is redundant, use ! with function calls instead
- Fixed a bug with get_gravatar

1.0.0
Initial release of util.php.