Designation: <item> — static property/method; # <item> — protected property/method
Array helper.
default delimiter for path()
Binary search algorithm.
Creates a callable function and parameter list from a string representation. Note that this function does not validate the callback string.
// Get the callback function and parameters
list($func, $params) = Arr::callback('Foo::bar(apple,orange)');
// Get the result of the callback
$result = call_user_func_array($func, $params);
Retrieves multiple keys from an array. If the key does not exist in the array, the default value will be added instead.
// Get the values "username", "password" from $_POST
$auth = Arr::extract($_POST, array('username', 'password'));
Convert a multi-dimensional array into a single-dimensional array.
$array = array('set' => array('one' => 'something'), 'two' => 'other');
// Flatten the array
$array = Arr::flatten($array);
// The array will now be
array('one' => 'something', 'two' => 'other');
The keys of array values will be discarded.
Retrieve a single key from an array. If the key does not exist in the array, the default value will be returned instead.
// Get the value "username" from $_POST, if it exists
$username = Arr::get($_POST, 'username');
// Get the value "sorting" from $_GET, if it exists
$sorting = Arr::get($_GET, 'sorting');
Test if a value is an array with an additional check for array-like objects.
// Returns TRUE
Arr::is_array(array());
Arr::is_array(new ArrayObject);
// Returns FALSE
Arr::is_array(FALSE);
Arr::is_array('not an array!');
Arr::is_array(Database::instance());
Tests if an array is associative or not.
// Returns TRUE
Arr::is_assoc(array('username' => 'john.doe'));
// Returns FALSE
Arr::is_assoc(array('foo', 'bar'));
Recursive version of array_map, applies the same callback to all elements in an array, including sub-arrays.
// Apply "strip_tags" to every element in the array
$array = Arr::map('strip_tags', $array);
Unlike array_map, this method requires a callback and will only map
a single array.
Merges one or more arrays recursively and preserves all keys. Note that this does not work the same as array_merge_recursive!
$john = array('name' => 'john', 'children' => array('fred', 'paul', 'sally', 'jane'));
$mary = array('name' => 'mary', 'children' => array('jane'));
// John and Mary are married, merge them together
$john = Arr::merge($john, $mary);
// The output of $john will now be:
array('name' => 'mary', 'children' => array('fred', 'paul', 'sally', 'jane'))
Overwrites an array with values from input arrays. Keys that do not exist in the first array will not be added!
$a1 = array('name' => 'john', 'mood' => 'happy', 'food' => 'bacon');
$a2 = array('name' => 'jack', 'food' => 'tacos', 'drink' => 'beer');
// Overwrite the values of $a1 with $a2
$array = Arr::overwrite($a1, $a2);
// The output of $array will now be:
array('name' => 'jack', 'mood' => 'happy', 'food' => 'tacos')
Gets a value from an array using a dot separated path.
// Get the value of $array['foo']['bar']
$value = Arr::path($array, 'foo.bar');
Using a wildcard "*" will search intermediate arrays and return an array.
// Get the values of "color" in theme
$colors = Arr::path($array, 'theme.*.color');
// Using an array of keys
$colors = Arr::path($array, array('theme', '*', 'color'));
Retrieves muliple single-key values from a list of arrays.
// Get all of the "id" values from a result
$ids = Arr::pluck($result, 'id');
A list of arrays is an array that contains arrays, eg: array(array $a, array $b, array $c, ...)
Fill an array with a range of numbers.
// Fill an array with values 5, 10, 15, 20
$values = Arr::range(5, 20);
Adds a value to the beginning of an associative array.
// Add an empty value to the start of a select list
Arr::unshift($array, 'none', 'Select a value');
Helper functions for working in a command-line environment.
Returns one or more command-line options. Options are specified using standard CLI syntax:
php index.php --username=john.smith --password=secret --var="some value with spaces"
// Get the values of "username" and "password"
$auth = CLI::options('username', 'password');
Cookie helper.
Restrict the domain that the cookie is available to
Number of seconds before the cookie expires
Only transmit cookies over HTTP, disabling Javascript access
Restrict the path that the cookie is available to
Magic salt to add to the cookie
Only transmit cookies over secure connections
Deletes a cookie by making the value NULL and expiring it.
Cookie::delete('theme');
Gets the value of a signed cookie. Cookies without signatures will not be returned. If the cookie signature is present, but invalid, the cookie will be deleted.
// Get the "theme" cookie, or use "blue" if the cookie does not exist
$theme = Cookie::get('theme', 'blue');
Generates a salt string for a cookie based on the name and value.
$salt = Cookie::salt('theme', 'red');
Sets a signed cookie. Note that all cookie values must be strings and no automatic serialization will be performed!
// Set the "theme" cookie
Cookie::set('theme', 'red');
Date helper.
Default timestamp format for formatted_time
Timezone for formatted_time
Adjusts a non-24-hour number into a 24-hour number.
$hour = Date::adjust(3, 'pm'); // 15
Returns AM or PM, based on a given hour (in 24 hour format).
$type = Date::ampm(12); // PM
$type = Date::ampm(1); // AM
Number of days in a given month and year. Typically used as a shortcut for generating a list that can be used in a form.
Date::days(4, 2010); // 1, 2, 3, ..., 28, 29, 30
Converts a DOS timestamp to UNIX format.There are very few cases where this is needed, but some binary formats use it (eg: zip files.) Converting the other direction is done using {@link Date::unix2dos}.
$unix = Date::dos2unix($dos);
Returns a date/time string with the specified timestamp format
$time = Date::formatted_time('5 minutes ago');
Returns the difference between a time and now in a "fuzzy" way. Displaying a fuzzy time instead of a date is usually faster to read and understand.
$span = Date::fuzzy_span(time() - 10); // "moments ago"
$span = Date::fuzzy_span(time() + 20); // "in moments"
A second parameter is available to manually set the "local" timestamp, however this parameter shouldn't be needed in normal usage and is only included for unit tests
Number of hours in a day. Typically used as a shortcut for generating a list that can be used in a form.
$hours = Date::hours(); // 01, 02, 03, ..., 10, 11, 12
Number of minutes in an hour, incrementing by a step. Typically used as a shortcut for generating a list that can be used in a form.
$minutes = Date::minutes(); // 05, 10, 15, ..., 50, 55, 60
Number of months in a year. Typically used as a shortcut for generating a list that can be used in a form.
Date::months(); // 01, 02, 03, ..., 10, 11, 12
Returns the offset (in seconds) between two time zones. Use this to display dates to users in different time zones.
$seconds = Date::offset('America/Chicago', 'GMT');
A list of time zones that PHP supports can be found at http://php.net/timezones.
Number of seconds in a minute, incrementing by a step. Typically used as a shortcut for generating a list that can used in a form.
$seconds = Date::seconds(); // 01, 02, 03, ..., 58, 59, 60
Returns time difference between two timestamps, in human readable format. If the second timestamp is not given, the current time will be used. Also consider using Date::fuzzy_span when displaying a span.
$span = Date::span(60, 182, 'minutes,seconds'); // array('minutes' => 2, 'seconds' => 2)
$span = Date::span(60, 182, 'minutes'); // 2
Converts a UNIX timestamp to DOS format. There are very few cases where this is needed, but some binary formats use it (eg: zip files.) Converting the other direction is done using {@link Date::dos2unix}.
$dos = Date::unix2dos($unix);
Returns an array of years between a starting and ending year. By default, the the current year - 5 and current year + 5 will be used. Typically used as a shortcut for generating a list that can be used in a form.
$years = Date::years(2000, 2010); // 2000, 2001, ..., 2009, 2010
The Encrypt library provides two-way encryption of text and binary strings using the Mcrypt extension, which consists of three parts: the key, the cipher, and the mode.
default instance name
Encrypt class instances
OS-dependent RAND type to use
Decrypts an encoded string back to its original value.
$data = $encrypt->decode($data);
Encrypts a string and returns an encrypted string that can be decoded.
$data = $encrypt->encode($data);
The encrypted binary data is encoded using base64 to convert it to a string. This string can be stored in a database, displayed, and passed using most other means without corruption.
Returns a singleton instance of Encrypt. An encryption key must be provided in your "encrypt" configuration file.
$encrypt = Encrypt::instance();
RSS and Atom feed helper.
Creates a feed from the given parameters.
Parses a remote feed into an array.
File helper class.
Join a split file into a whole file. Does the reverse of File::split.
$count = File::join($file);
Attempt to get the mime type from a file. This method is horribly unreliable, due to PHP being horribly unreliable when it comes to determining the mime type of a file.
$mime = File::mime($file);
Return the mime type of an extension.
$mime = File::mime_by_ext('png'); // "image/png"
Split a file into pieces matching a specific size. Used when you need to split large files into smaller pieces for easy transmission.
$count = File::split($file);
Form helper class. Unless otherwise noted, all generated HTML will be made safe using the HTML::chars method. This prevents against simple XSS attacks that could otherwise be trigged by inserting HTML characters into form fields.
Creates a button form input. Note that the body of a button is NOT escaped, to allow images and other HTML to be used.
echo Form::button('save', 'Save Profile', array('type' => 'submit'));
Creates a checkbox form input.
echo Form::checkbox('remember_me', 1, (bool) $remember);
Creates the closing form tag.
echo Form::close();
Creates a file upload form input. No input value can be specified.
echo Form::file('image');
Creates a hidden form input.
echo Form::hidden('csrf', $token);
Creates a image form input.
echo Form::image(NULL, NULL, array('src' => 'media/img/login.png'));
Creates a form input. If no type is specified, a "text" type input will be returned.
echo Form::input('username', $username);
Creates a form label. Label text is not automatically translated.
echo Form::label('username', 'Username');
Generates an opening HTML form tag.
// Form will submit back to the current page using POST
echo Form::open();
// Form will submit to 'search' using GET
echo Form::open('search', array('method' => 'get'));
// When "file" inputs are present, you must include the "enctype"
echo Form::open(NULL, array('enctype' => 'multipart/form-data'));
Creates a password form input.
echo Form::password('password');
Creates a radio form input.
echo Form::radio('like_cats', 1, $cats);
echo Form::radio('like_cats', 0, ! $cats);
Creates a select form input.
echo Form::select('country', $countries, $country);
Support for multiple selected options was added in v3.0.7.
Creates a submit form input.
echo Form::submit(NULL, 'Login');
Creates a textarea form input.
echo Form::textarea('about', $about);
View fragment caching. This is primarily used to cache small parts of a view that rarely change. For instance, you may want to cache the footer of your template because it has very little dynamic content. Or you could cache a user profile page and delete the fragment when the user updates.
For obvious reasons, fragment caching should not be applied to any content that contains forms.
Multiple language (I18n) support was added in v3.0.4.
use multilingual fragment support?
default number of seconds to cache for
list of buffer => cache key
Delete a cached fragment.
Fragment::delete($key);
Load a fragment from cache and display it. Multiple fragments can be nested with different life times.
if ( ! Fragment::load('footer')) {
// Anything that is echo'ed here will be saved
Fragment::save();
}
Saves the currently open fragment in the cache.
Fragment::save();
Generate the cache key name for a fragment.
$key = Fragment::_cache_key('footer', TRUE);
HTML helper class. Provides generic methods for generating various HTML tags and making output HTML safe.
preferred order of attributes
automatically target external URLs to a new window?
Create HTML link anchors. Note that the title is not escaped, to allow HTML elements within links (images, etc).
echo HTML::anchor('/user/profile', 'My Profile');
Compiles an array of HTML attributes into an attribute string. Attributes will be sorted using HTML::$attribute_order for consistency.
echo '<div'.HTML::attributes($attrs).'>'.$content.'</div>';
Convert special characters to HTML entities. All untrusted content should be passed through this method to prevent XSS injections.
echo HTML::chars($username);
Generates an obfuscated version of an email address. Helps prevent spam robots from finding email addresses.
echo HTML::email($address);
Convert all applicable characters to HTML entities. All characters that cannot be represented in HTML with the current character set will be converted to entities.
echo HTML::entities($username);
Creates an HTML anchor to a file. Note that the title is not escaped, to allow HTML elements within links (images, etc).
echo HTML::file_anchor('media/doc/user_guide.pdf', 'User Guide');
Creates a image link.
echo HTML::image('media/img/logo.png', array('alt' => 'My Company'));
Creates an email (mailto:) anchor. Note that the title is not escaped, to allow HTML elements within links (images, etc).
echo HTML::mailto($address);
Generates an obfuscated version of a string. Text passed through this method is less likely to be read by web crawlers and robots, which can be helpful for spam prevention, but can prevent legitimate robots from reading your content.
echo HTML::obfuscate($text);
Creates a script link.
echo HTML::script('media/js/jquery.min.js');
Creates a style sheet link element.
echo HTML::style('media/css/screen.css');
Internationalization (i18n) class. Provides language loading and translation methods without dependencies on gettext.
Typically this class would never be used directly, but used via the __() function, which loads the message and replaces parameters:
// Display a translated message
echo __('Hello, world');
// With parameter replacement
echo __('Hello, :user', array(':user' => $username));
The __() function is declared in SYSPATH/base.php.
target language: en-us, es-es, zh-cn, etc
source language: en-us, es-es, zh-cn, etc
cache of loaded languages
Returns translation of a string. If no translation exists, the original string will be returned. No parameters are replaced.
$hello = I18n::get('Hello friends, my name is :name');
Get and set the target language.
// Get the current language
$lang = I18n::lang();
// Change the current language to Spanish
I18n::lang('es-es');
Returns the translation table for a given language.
// Get all defined Spanish messages
$messages = I18n::load('es-es');
Inflector helper class. Inflection is changing the form of a word based on the context it is used in. For example, changing a word into a plural form.
Inflection is only tested with English, and is will not work with other languages.
cached inflections
irregular words
uncountable words
Makes a phrase camel case. Spaces and underscores will be removed.
$str = Inflector::camelize('mother cat'); // "motherCat"
$str = Inflector::camelize('kittens in bed'); // "kittensInBed"
Converts a camel case phrase into a spaced phrase.
$str = Inflector::decamelize('houseCat'); // "house cat"
$str = Inflector::decamelize('kingAllyCat'); // "king ally cat"
Makes an underscored or dashed phrase human-readable.
$str = Inflector::humanize('kittens-are-cats'); // "kittens are cats"
$str = Inflector::humanize('dogs_as_well'); // "dogs as well"
Makes a singular word plural.
echo Inflector::plural('fish'); // "fish", uncountable
echo Inflector::plural('cat'); // "cats"
You can also provide the count to make inflection more intelligent. In this case, it will only return the plural value if the count is not one.
echo Inflector::singular('cats', 3); // "cats"
Special inflections are defined in config/inflector.php.
Makes a plural word singular.
echo Inflector::singular('cats'); // "cat"
echo Inflector::singular('fish'); // "fish", uncountable
You can also provide the count to make inflection more intelligent. In this case, it will only return the singular value if the count is greater than one and not zero.
echo Inflector::singular('cats', 2); // "cats"
Special inflections are defined in config/inflector.php.
Checks if a word is defined as uncountable. An uncountable word has a single form. For instance, one "fish" and many "fish", not "fishes".
Inflector::uncountable('fish'); // TRUE
Inflector::uncountable('cat'); // FALSE
If you find a word is being pluralized improperly, it has probably not
been defined as uncountable in config/inflector.php. If this is the
case, please report an issue.
Makes a phrase underscored instead of spaced.
$str = Inflector::underscore('five cats'); // "five_cats";
Wrapper for configuration arrays. Multiple configuration readers can be attached to allow loading configuration from files, database, etc.
Singleton static instance
Configuration readers
Attach a configuration reader. By default, the reader will be added as
the first used reader. However, if the reader should be used only when
all other readers fail, use FALSE for the second parameter.
$config->attach($reader); // Try first
$config->attach($reader, FALSE); // Try last
Copy one configuration group to all of the other readers.
$config->copy($name);
Detach a configuration reader.
$config->detach($reader);
Get the singleton instance of Kohana_Config.
$config = Kohana_Config::instance();
Load a configuration group. Searches the readers in order until the group is found. If the group does not exist, an empty configuration array will be loaded using the first reader.
$array = $config->load($name);
Contains the most low-level helpers methods in Kohana:
Default lifetime for caching, in seconds, used by Kohana::cache. Set by Kohana::init
Whether to use internal caching for Kohana::find_file, does not apply to Kohana::cache. Set by Kohana::init
config object
escape quotes in Kohana::debug?
Current environment name
Error rendering view when Kohana catches PHP errors and exceptions. Set by Kohana::init
Enable Kohana catching and displaying PHP errors and exceptions. Set by Kohana::init
Application index file, added to links generated by Kohana. Set by Kohana::init
True if Kohana is running from the command line
True if Kohana is running on windows
logging object
Should errors and exceptions be logged
Codes to turn PHP error codes into readable names.
TRUE if PHP safe mode is on
Types of errors to display at shutdown
Has the file path cache changed during this execution? Used internally when when caching is true in Kohana::init
Currently active modules
Include paths that are used to find files
Provides auto-loading support of classes that follow Kohana's class naming conventions. See Loading Classes for more information.
Class names are converted to file names by making the class name lowercase and converting underscores to slashes:
// Loads classes/my/class/name.php
Kohana::auto_load('My_Class_Name');
You should never have to call this function, as simply calling a class will cause it to be called.
This function must be enabled as an autoloader in the bootstrap:
spl_autoload_register(array('Kohana', 'auto_load'));
Provides simple file-based caching for strings and arrays:
// Set the "foo" cache
Kohana::cache('foo', 'hello, world');
// Get the "foo" cache
$foo = Kohana::cache('foo');
All caches are stored as PHP code, generated with var_export. Caching objects may not work as expected. Storing references or an object or array that has recursion will cause an E_FATAL.
The cache directory and default cache lifetime is set by Kohana::init
Returns the configuration array for the requested group. See configuration files for more information.
// Get all the configuration in config/database.php
$config = Kohana::config('database');
// Get only the default connection configuration
$default = Kohana::config('database.default')
// Get only the hostname of the default connection
$host = Kohana::config('database.default.connection.hostname')
Returns an HTML string of debugging information about any number of variables, each wrapped in a "pre" tag:
// Displays the type and value of each variable
echo Kohana::debug($foo, $bar, $baz);
Removes application, system, modpath, or docroot from a filename, replacing them with the plain text equivalents. Useful for debugging when you want to display a shorter path.
// Displays SYSPATH/classes/kohana.php
echo Kohana::debug_path(Kohana::find_file('classes', 'kohana'));
Returns an HTML string, highlighting a specific line of a file, with some number of lines padded above and below.
// Highlights the current line of the current file
echo Kohana::debug_source(__FILE__, __LINE__);
Cleans up the environment:
Returns an HTML string of information about a single variable.
Borrows heavily on concepts from the Debug class of Nette.
PHP error handler, converts all errors into ErrorExceptions. This handler respects error_reporting settings.
Inline exception handler, displays the error message, source of the exception, and the stack trace of the error.
Get a single line of text representing the exception:
Error [ Code ]: Message ~ File [ Line ]
Searches for a file in the Cascading Filesystem, and returns the path to the file that has the highest precedence, so that it can be included.
When searching the "config", "messages", or "i18n" directories, or when
the $array flag is set to true, an array of all the files that match
that path in the Cascading Filesystem will be returned.
These files will return arrays which must be merged together.
If no extension is given, the default extension (EXT set in
index.php) will be used.
// Returns an absolute path to views/template.php
Kohana::find_file('views', 'template');
// Returns an absolute path to media/css/style.css
Kohana::find_file('media', 'css/style', 'css');
// Returns an array of all the "mimes" configuration files
Kohana::find_file('config', 'mimes');
Reverts the effects of the register_globals PHP setting by unsetting
all global varibles except for the default super globals (GPCS, etc),
which is a potential security hole.
This is called automatically by Kohana::init if register_globals is
on.
Returns the the currently active include paths, including the application, system, and each module's path.
Initializes the environment:
The following settings can be set:
| Type | Setting | Description | Default Value |
|---|---|---|---|
string |
base_url | The base URL for your application. This should be the relative path from your DOCROOT to your index.php file, in other words, if Kohana is in a subfolder, set this to the subfolder name, otherwise leave it as the default. The leading slash is required, trailing slash is optional. |
"/" |
string |
index_file | The name of the front controller. This is used by Kohana to generate relative urls like HTML::anchor() and URL::base(). This is usually index.php. To remove index.php from your urls, set this to FALSE. |
"index.php" |
string |
charset | Character set used for all input and output | "utf-8" |
string |
cache_dir | Kohana's cache directory. Used by Kohana::cache for simple internal caching, like Fragments and [caching database queries](this should link somewhere). This has nothing to do with the Cache module. | APPPATH."cache" |
integer |
cache_life | Lifetime, in seconds, of items cached by Kohana::cache | 60 |
boolean |
errors | Should Kohana catch PHP errors and uncaught Exceptions and show the error_view. See Error Handling for more info. Recommended setting: TRUE while developing, FALSE on production servers. |
TRUE |
string |
error_view | The view to use to display errors. Only used when errors is TRUE. |
"kohana/error" |
boolean |
profile | Whether to enable the Profiler. Recommended setting: TRUE while developing, FALSE on production servers. |
TRUE |
boolean |
caching | Cache file locations to speed up Kohana::find_file. This has nothing to do with Kohana::cache, Fragments or the Cache module. Recommended setting: FALSE while developing, TRUE on production servers. |
FALSE |
Recursively finds all of the files in the specified directory at any location in the Cascading Filesystem, and returns an array of all the files found, sorted alphabetically.
// Find all view files.
$views = Kohana::list_files('views');
Loads a file within a totally empty scope and returns the output:
$foo = Kohana::load('foo.php');
Get a message from a file. Messages are arbitary strings that are stored
in the messages/ directory and reference by a key. Translation is not
performed on the returned values. See message files
for more information.
// Get "username" from messages/text.php
$username = Kohana::message('text', 'username');
Changes the currently enabled modules. Module paths may be relative or absolute, but must point to a directory:
Kohana::modules(array('modules/foo', MODPATH.'bar'));
Recursively sanitizes an input variable:
Catches errors that are not caught by the error handler, such as E_PARSE.
Returns an array of HTML strings that represent each step in the backtrace.
// Displays the entire current backtrace
echo implode('<br/>', Kohana::trace());
Helper for Kohana::dump(), handles recursion in arrays and objects.
Message logging with observer-based log writing.
This class does not support extensions, only additional writers.
timestamp format for log entries
timezone for log entries
immediately write when logs are added
Singleton instance container
list of added messages
list of log writers
Adds a message to the log. Replacement values must be passed in to be replaced using strtr.
$log->add('error', 'Could not locate user: :user', array(
':user' => $username,
));
Attaches a log writer, and optionally limits the types of messages that will be written by the writer.
$log->attach($writer);
Detaches a log writer. The same writer object must be used.
$log->detach($writer);
Get the singleton instance of this class and enable writing at shutdown.
$log = Kohana_Log::instance();
Write and clear all of the messages.
$log->write();
Contains the most low-level helpers methods in Kohana:
Default lifetime for caching, in seconds, used by Kohana::cache. Set by Kohana::init
Whether to use internal caching for Kohana::find_file, does not apply to Kohana::cache. Set by Kohana::init
config object
escape quotes in Kohana::debug?
Current environment name
Error rendering view when Kohana catches PHP errors and exceptions. Set by Kohana::init
Enable Kohana catching and displaying PHP errors and exceptions. Set by Kohana::init
Application index file, added to links generated by Kohana. Set by Kohana::init
True if Kohana is running from the command line
True if Kohana is running on windows
logging object
Should errors and exceptions be logged
Codes to turn PHP error codes into readable names.
TRUE if PHP safe mode is on
Types of errors to display at shutdown
Has the file path cache changed during this execution? Used internally when when caching is true in Kohana::init
Currently active modules
Include paths that are used to find files
Provides auto-loading support of classes that follow Kohana's class naming conventions. See Loading Classes for more information.
Class names are converted to file names by making the class name lowercase and converting underscores to slashes:
// Loads classes/my/class/name.php
Kohana::auto_load('My_Class_Name');
You should never have to call this function, as simply calling a class will cause it to be called.
This function must be enabled as an autoloader in the bootstrap:
spl_autoload_register(array('Kohana', 'auto_load'));
Provides simple file-based caching for strings and arrays:
// Set the "foo" cache
Kohana::cache('foo', 'hello, world');
// Get the "foo" cache
$foo = Kohana::cache('foo');
All caches are stored as PHP code, generated with var_export. Caching objects may not work as expected. Storing references or an object or array that has recursion will cause an E_FATAL.
The cache directory and default cache lifetime is set by Kohana::init
Returns the configuration array for the requested group. See configuration files for more information.
// Get all the configuration in config/database.php
$config = Kohana::config('database');
// Get only the default connection configuration
$default = Kohana::config('database.default')
// Get only the hostname of the default connection
$host = Kohana::config('database.default.connection.hostname')
Returns an HTML string of debugging information about any number of variables, each wrapped in a "pre" tag:
// Displays the type and value of each variable
echo Kohana::debug($foo, $bar, $baz);
Removes application, system, modpath, or docroot from a filename, replacing them with the plain text equivalents. Useful for debugging when you want to display a shorter path.
// Displays SYSPATH/classes/kohana.php
echo Kohana::debug_path(Kohana::find_file('classes', 'kohana'));
Returns an HTML string, highlighting a specific line of a file, with some number of lines padded above and below.
// Highlights the current line of the current file
echo Kohana::debug_source(__FILE__, __LINE__);
Cleans up the environment:
Returns an HTML string of information about a single variable.
Borrows heavily on concepts from the Debug class of Nette.
PHP error handler, converts all errors into ErrorExceptions. This handler respects error_reporting settings.
Inline exception handler, displays the error message, source of the exception, and the stack trace of the error.
Get a single line of text representing the exception:
Error [ Code ]: Message ~ File [ Line ]
Searches for a file in the Cascading Filesystem, and returns the path to the file that has the highest precedence, so that it can be included.
When searching the "config", "messages", or "i18n" directories, or when
the $array flag is set to true, an array of all the files that match
that path in the Cascading Filesystem will be returned.
These files will return arrays which must be merged together.
If no extension is given, the default extension (EXT set in
index.php) will be used.
// Returns an absolute path to views/template.php
Kohana::find_file('views', 'template');
// Returns an absolute path to media/css/style.css
Kohana::find_file('media', 'css/style', 'css');
// Returns an array of all the "mimes" configuration files
Kohana::find_file('config', 'mimes');
Reverts the effects of the register_globals PHP setting by unsetting
all global varibles except for the default super globals (GPCS, etc),
which is a potential security hole.
This is called automatically by Kohana::init if register_globals is
on.
Returns the the currently active include paths, including the application, system, and each module's path.
Initializes the environment:
The following settings can be set:
| Type | Setting | Description | Default Value |
|---|---|---|---|
string |
base_url | The base URL for your application. This should be the relative path from your DOCROOT to your index.php file, in other words, if Kohana is in a subfolder, set this to the subfolder name, otherwise leave it as the default. The leading slash is required, trailing slash is optional. |
"/" |
string |
index_file | The name of the front controller. This is used by Kohana to generate relative urls like HTML::anchor() and URL::base(). This is usually index.php. To remove index.php from your urls, set this to FALSE. |
"index.php" |
string |
charset | Character set used for all input and output | "utf-8" |
string |
cache_dir | Kohana's cache directory. Used by Kohana::cache for simple internal caching, like Fragments and [caching database queries](this should link somewhere). This has nothing to do with the Cache module. | APPPATH."cache" |
integer |
cache_life | Lifetime, in seconds, of items cached by Kohana::cache | 60 |
boolean |
errors | Should Kohana catch PHP errors and uncaught Exceptions and show the error_view. See Error Handling for more info. Recommended setting: TRUE while developing, FALSE on production servers. |
TRUE |
string |
error_view | The view to use to display errors. Only used when errors is TRUE. |
"kohana/error" |
boolean |
profile | Whether to enable the Profiler. Recommended setting: TRUE while developing, FALSE on production servers. |
TRUE |
boolean |
caching | Cache file locations to speed up Kohana::find_file. This has nothing to do with Kohana::cache, Fragments or the Cache module. Recommended setting: FALSE while developing, TRUE on production servers. |
FALSE |
Recursively finds all of the files in the specified directory at any location in the Cascading Filesystem, and returns an array of all the files found, sorted alphabetically.
// Find all view files.
$views = Kohana::list_files('views');
Loads a file within a totally empty scope and returns the output:
$foo = Kohana::load('foo.php');
Get a message from a file. Messages are arbitary strings that are stored
in the messages/ directory and reference by a key. Translation is not
performed on the returned values. See message files
for more information.
// Get "username" from messages/text.php
$username = Kohana::message('text', 'username');
Changes the currently enabled modules. Module paths may be relative or absolute, but must point to a directory:
Kohana::modules(array('modules/foo', MODPATH.'bar'));
Recursively sanitizes an input variable:
Catches errors that are not caught by the error handler, such as E_PARSE.
Returns an array of HTML strings that represent each step in the backtrace.
// Displays the entire current backtrace
echo implode('<br/>', Kohana::trace());
Helper for Kohana::dump(), handles recursion in arrays and objects.
Model base class. All models should extend this class.
database instance
Create a new model instance. A Database instance or configuration group name can be passed to the model. If no database is defined, the "default" database group will be used.
$model = Model::factory($name);
Number helper class. Provides additional formatting methods that for working with numbers.
Locale-aware number and monetary formatting.
// In English, "1,200.05"
// In Spanish, "1200,05"
// In Portuguese, "1 200,05"
echo Num::format(1200.05, 2);
// In English, "1,200.05"
// In Spanish, "1.200,05"
// In Portuguese, "1.200.05"
echo Num::format(1200.05, 2, TRUE);
Returns the English ordinal suffix (th, st, nd, etc) of a number.
echo 2, Num::ordinal(2); // "2nd"
echo 10, Num::ordinal(10); // "10th"
echo 33, Num::ordinal(33); // "33rd"
Provides simple benchmarking and profiling. To display the statistics that
have been collected, load the profiler/stats View:
echo View::factory('profiler/stats');
maximium number of application stats to keep
collected benchmarks
Gets the total application run time and memory usage. Caches the result so that it can be compared between requests.
list($time, $memory) = Profiler::application();
Deletes a benchmark. If an error occurs during the benchmark, it is recommended to delete the benchmark to prevent statistics from being adversely affected.
Profiler::delete($token);
Gets the min, max, average and total of profiler groups as an array.
$stats = Profiler::group_stats('test');
Returns all the benchmark tokens by group and name as an array.
$groups = Profiler::groups();
Starts a new benchmark and returns a unique token. The returned token must be used when stopping the benchmark.
$token = Profiler::start('test', 'profiler');
Gets the min, max, average and total of a set of tokens as an array.
$stats = Profiler::stats($tokens);
Stops a benchmark.
Profiler::stop($token);
Gets the total execution time and memory usage of a benchmark as a list.
list($time, $memory) = Profiler::total($token);
Provides remote server communications options using curl.
default cURL options
Returns the output of a remote URL. Any curl option may be used.
// Do a simple GET request
$data = Remote::get($url);
// Do a POST request
$data = Remote::get($url, array(
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => http_build_query($array),
));
Returns the status code (200, 500, etc) for a URL.
$status = Remote::status($url);
Request and response wrapper. Uses the Route class to determine what Controller to send the request to.
action to be executed in the controller
client IP address
controller to be executed
currently executing request instance
controller directory
headers to send with the response body
main request instance
AJAX-generated request
HTTP status codes and messages
method: GET, POST, PUT, DELETE, etc
protocol: http, https, ftp, cli, etc
referring URL
response body
route matched for this request
HTTP response code: 200, 404, 500, etc
the URI of the request
client user agent
Returns the accepted encodings. If a specific encoding is defined, the quality of that encoding will be returned. If the encoding is not accepted, FALSE will be returned.
$encodings = Request::accept_encoding();
Returns the accepted languages. If a specific language is defined, the quality of that language will be returned. If the language is not accepted, FALSE will be returned.
$langs = Request::accept_lang();
Returns the accepted content types. If a specific type is defined, the quality of that type will be returned.
$types = Request::accept_type();
Checks the browser cache to see the response needs to be returned.
$request->check_cache($etag);
If the cache check succeeds, no further processing can be done!
Return the currently executing request. This is changed to the current request when Request::execute is called and restored when the request is completed.
$request = Request::current();
Automatically detects the URI of the main request using PATH_INFO, REQUEST_URI, PHP_SELF or REDIRECT_URL.
$uri = Request::detect_uri();
Processes the request, executing the controller action that handles this request, determined by the Route.
By default, the output from the controller is captured and returned, and no headers are sent.
$request->execute();
Creates a new request object for the given URI. This differs from Request::instance in that it does not automatically detect the URI and should only be used for creating HMVC requests.
$request = Request::factory($uri);
Generates an ETag from the request response.
$etag = $request->generate_etag();
If the request response is empty when this method is called, an exception will be thrown!
Main request singleton instance. If no URI is provided, the URI will be automatically detected.
$request = Request::instance();
Retrieves a value from the route parameters.
$id = $request->param('id');
Redirects as the request response. If the URL does not include a protocol, it will be converted into a complete URL.
$request->redirect($url);
No further processing can be done after this method is called!
Send file download as the response. All execution will be halted when this method is called! Use TRUE for the filename to send the current response as the file content. The third parameter allows the following options to be set:
| Type | Option | Description | Default Value |
|---|---|---|---|
boolean |
inline | Display inline instead of download | FALSE |
string |
mime_type | Manual mime type | Automatic |
boolean |
delete | Delete the file after sending | FALSE |
Download a file that already exists:
$request->send_file('media/packages/kohana.zip');
Download generated content as a file:
$request->response = $content;
$request->send_file(TRUE, $filename);
No further processing can be done after this method is called!
Sends the response status and all set headers. The current server protocol (HTTP/1.0 or HTTP/1.1) will be used when available. If not available, HTTP/1.1 will be used.
$request->send_headers();
Generates a relative URI for the current route.
$request->uri($params);
Create a URL from the current request. This is a shortcut for:
echo URL::site($this->request->uri($params), $protocol);
Returns information about the client user agent.
// Returns "Chrome" when using Google Chrome
$browser = Request::user_agent('browser');
Multiple values can be returned at once by using an array:
// Get the browser and platform with a single call
$info = Request::user_agent(array('browser', 'platform'));
When using an array for the value, an associative array will be returned.
Calculates the byte range to use with send_file. If HTTP_RANGE doesn't exist then the complete byte range is returned
Parses an accept header and returns an array (type => quality) of the accepted types, ordered by quality.
$accept = Request::_parse_accept($header, $defaults);
Parse the byte ranges from the HTTP_RANGE header used for resumable downloads.
Routes are used to determine the controller and action for a requested URI. Every route generates a regular expression which is used to match a URI and a route. Routes may also contain keys which can be used to set the controller, action, and parameters.
Each
// This route will only match when <id> is a digit
Route::set('user', 'user/<action>/<id>', array('id' => '\d+'));
// This route will match when <path> is anything
Route::set('file', '<path>', array('path' => '.*'));
It is also possible to create optional segments by using parentheses in the URI definition:
// This is the standard default route, and no keys are required
Route::set('default', '(<controller>(/<action>(/<id>)))');
// This route only requires the <file> key
Route::set('file', '(<path>/)<file>(.<format>)', array('path' => '.*', 'format' => '\w+'));
Routes also provide a way to generate URIs (called "reverse routing"), which makes them an extremely powerful and flexible way to generate internal links.
default action for all routes
list of route objects
Retrieves all named routes.
$routes = Route::all();
Saves or loads the route cache. If your routes will remain the same for a long period of time, use this to reload the routes from the cache rather than redefining them on every page load.
if ( ! Route::cache())
{
// Set routes here
Route::cache(TRUE);
}
Provides default values for keys when they are not present. The default action will always be "index" unless it is overloaded here.
$route->defaults(array(
'controller' => 'welcome',
'action' => 'index'
));
Retrieves a named route.
$route = Route::get('default');
Tests if the route matches a given URI. A successful match will return all of the routed parameters as an array. A failed match will return boolean FALSE.
// Params: controller = users, action = edit, id = 10
$params = $route->matches('users/edit/10');
This method should almost always be used within an if/else block:
if ($params = $route->matches($uri))
{
// Parse the parameters
}
Get the name of a route.
$name = Route::name($route)
Stores a named route and returns it. The "action" will always be set to "index" if it is not defined.
Route::set('default', '(<controller>(/<action>(/<id>)))')
->defaults(array(
'controller' => 'welcome',
));
Generates a URI for the current route based on the parameters given.
// Using the "default" route: "users/profile/10"
$route->uri(array(
'controller' => 'users',
'action' => 'profile',
'id' => '10'
));
Create a URL from a route name. This is a shortcut for:
echo URL::site(Route::get($name)->uri($params), $protocol);
Returns the compiled regular expression for the route. This translates keys and optional groups to a proper PCRE regular expression.
$regex = $route->_compile();
Security helper class.
key name used for token storage
Check that the given token matches the currently stored security token.
if (Security::check($token))
{
// Pass
}
Encodes PHP tags in a string.
$str = Security::encode_php_tags($str);
Remove image tags from a string.
$str = Security::strip_image_tags($str);
Generate and store a unique token which can be used to help prevent CSRF attacks.
$token = Security::token();
You can insert this token into your forms as a hidden field:
echo Form::hidden('csrf', Security::token());
And then check it when using Validate:
$array->rules('csrf', array(
'not_empty' => NULL,
'Security::check' => NULL,
));
This provides a basic, but effective, method of preventing CSRF attacks.
Remove XSS from user input.
$str = Security::xss_clean($str);
Cookie-based session class.
default session adapter
session instances
session data
session destroyed?
encrypt session data?
cookie lifetime
cookie name
Returns the current session array. The returned array can also be assigned by reference.
// Get a copy of the current session data
$data = $session->as_array();
// Assign by reference for modification
$data =& $session->as_array();
Set a variable by reference.
$session->bind('foo', $foo);
Removes a variable in the session array.
$session->delete('foo');
Completely destroy the current session.
$success = $session->destroy();
Get a variable from the session array.
$foo = $session->get('foo');
Get and delete a variable from the session array.
$bar = $session->get_once('bar');
Get the current session id, if the session supports it.
$id = $session->id();
Not all session types have ids.
Creates a singleton session of the given type. Some session types (native, database) also support restarting a session by passing a session id as the second parameter.
$session = Session::instance();
Session::write will automatically be called when the request ends.
Get the current session cookie name.
$name = $session->name();
Loads existing session data.
$session->read();
Generates a new session id and returns it.
$id = $session->regenerate();
Set a variable in the session array.
$session->set('foo', 'bar');
Sets the last_active timestamp and saves the session.
$session->write();
Any errors that occur during session writing will be logged, but not displayed, because sessions are written after output has been sent.
Native PHP session class.
default session adapter
session instances
session data
session destroyed?
encrypt session data?
cookie lifetime
cookie name
Returns the current session array. The returned array can also be assigned by reference.
// Get a copy of the current session data
$data = $session->as_array();
// Assign by reference for modification
$data =& $session->as_array();
Set a variable by reference.
$session->bind('foo', $foo);
Removes a variable in the session array.
$session->delete('foo');
Completely destroy the current session.
$success = $session->destroy();
Get a variable from the session array.
$foo = $session->get('foo');
Get and delete a variable from the session array.
$bar = $session->get_once('bar');
Creates a singleton session of the given type. Some session types (native, database) also support restarting a session by passing a session id as the second parameter.
$session = Session::instance();
Session::write will automatically be called when the request ends.
Get the current session cookie name.
$name = $session->name();
Loads existing session data.
$session->read();
Generates a new session id and returns it.
$id = $session->regenerate();
Set a variable in the session array.
$session->set('foo', 'bar');
Sets the last_active timestamp and saves the session.
$session->write();
Any errors that occur during session writing will be logged, but not displayed, because sessions are written after output has been sent.
Base session class.
default session adapter
session instances
session data
session destroyed?
encrypt session data?
cookie lifetime
cookie name
Returns the current session array. The returned array can also be assigned by reference.
// Get a copy of the current session data
$data = $session->as_array();
// Assign by reference for modification
$data =& $session->as_array();
Set a variable by reference.
$session->bind('foo', $foo);
Removes a variable in the session array.
$session->delete('foo');
Completely destroy the current session.
$success = $session->destroy();
Get a variable from the session array.
$foo = $session->get('foo');
Get and delete a variable from the session array.
$bar = $session->get_once('bar');
Get the current session id, if the session supports it.
$id = $session->id();
Not all session types have ids.
Creates a singleton session of the given type. Some session types (native, database) also support restarting a session by passing a session id as the second parameter.
$session = Session::instance();
Session::write will automatically be called when the request ends.
Get the current session cookie name.
$name = $session->name();
Loads existing session data.
$session->read();
Generates a new session id and returns it.
$id = $session->regenerate();
Set a variable in the session array.
$session->set('foo', 'bar');
Sets the last_active timestamp and saves the session.
$session->write();
Any errors that occur during session writing will be logged, but not displayed, because sessions are written after output has been sent.
Destroys the current session.
Loads the raw session data string and returns it.
Generate a new session id and return it.
Writes the current session.
Text helper class. Provides simple methods for working with text.
number units and text equivalents
Alternates between two or more strings.
echo Text::alternate('one', 'two'); // "one"
echo Text::alternate('one', 'two'); // "two"
echo Text::alternate('one', 'two'); // "one"
Note that using multiple iterations of different strings may produce unexpected results.
Converts text email addresses and anchors into links. Existing links will not be altered.
echo Text::auto_link($text);
This method is not foolproof since it uses regex to parse HTML.
Converts text email addresses into links. Existing links will not be altered.
echo Text::auto_link_emails($text);
This method is not foolproof since it uses regex to parse HTML.
Converts text anchors into links. Existing links will not be altered.
echo Text::auto_link_urls($text);
This method is not foolproof since it uses regex to parse HTML.
Automatically applies "p" and "br" markup to text. Basically nl2br on steroids.
echo Text::auto_p($text);
This method is not foolproof since it uses regex to parse HTML.
Returns human readable sizes. Based on original functions written by Aidan Lister and Quentin Zervaas.
echo Text::bytes(filesize($file));
Replaces the given words with a string.
// Displays "What the #####, man!"
echo Text::censor('What the frick, man!', array(
'frick' => '#####',
));
Limits a phrase to a given number of characters.
$text = Text::limit_chars($text);
Limits a phrase to a given number of words.
$text = Text::limit_words($text);
Format a number to human-readable text.
// Display: one thousand and twenty-four
echo Text::number(1024);
// Display: five million, six hundred and thirty-two
echo Text::number(5000632);
Generates a random string of a given type and length.
$str = Text::random(); // 8 character random string
The following types are supported:
You can also create a custom type by providing the "pool" of characters as the type.
Reduces multiple slashes in a string to single slashes.
$str = Text::reduce_slashes('foo//bar/baz'); // "foo/bar/baz"
Finds the text that is similar between a set of words.
$match = Text::similar(array('fred', 'fran', 'free'); // "fr"
Prevents widow words by inserting a non-breaking space between the last two words.
echo Text::widont($text);
Upload helper class for working with uploaded files and Validate.
$array = Validate::factory($_FILES);
Remember to define your form with "enctype=multipart/form-data" or file uploading will not work!
The following configuration properties can be set:
default upload directory
remove spaces in uploaded files
Tests if a successful upload has been made.
$array->rule('file', 'Upload::not_empty');
Save an uploaded file to a new location. If no filename is provided, the original filename will be used, with a unique prefix added.
This method should be used after validating the $_FILES array:
if ($array->check())
{
// Upload is valid, save it
Upload::save($_FILES['file']);
}
Validation rule to test if an uploaded file is allowed by file size. File sizes are defined as: SB, where S is the size (1, 15, 300, etc) and B is the byte modifier: (B)ytes, (K)ilobytes, (M)egabytes, (G)igabytes.
$array->rule('file', 'Upload::size', array('1M'))
Test if an uploaded file is an allowed file type, by extension.
$array->rule('file', 'Upload::type', array(array('jpg', 'png', 'gif')));
Tests if upload data is valid, even if no file was uploaded. If you do require a file to be uploaded, add the Upload::not_empty rule before this rule.
$array->rule('file', 'Upload::valid')
URL helper class.
Gets the base URL to the application. To include the current protocol,
use TRUE. To specify a protocol, provide the protocol as a string.
If a protocol is used, a complete URL will be generated using the
$_SERVER['HTTP_HOST'] variable.
// Absolute relative, no host or protocol
echo URL::base();
// Complete relative, with host and protocol
echo URL::base(TRUE, TRUE);
// Complete relative, with host and "https" protocol
echo URL::base(TRUE, 'https');
Merges the current GET parameters with an array of new or overloaded parameters and returns the resulting query string.
// Returns "?sort=title&limit=10" combined with any existing GET values
$query = URL::query(array('sort' => 'title', 'limit' => 10));
Typically you would use this when you are sorting query results, or something similar.
Parameters with a NULL value are left out.
Fetches an absolute site URL based on a URI segment.
echo URL::site('foo/bar');
Convert a phrase to a URL-safe title.
echo URL::title('My Blog Post'); // "my-blog-post"
A port of phputf8 to a unified set of files. Provides multi-byte aware replacement string functions.
For UTF-8 support to work correctly, the following requirements must be met:
This file is licensed differently from the rest of Kohana. As a port of phputf8, this file is released under the LGPL.
List of called methods that have had their required file included.
Does the server support UTF-8 natively?
Recursively cleans arrays, objects, and strings. Removes ASCII control codes and converts to the requested charset while silently discarding incompatible characters.
UTF8::clean($_GET); // Clean GET data
This method requires Iconv
Takes an array of ints representing the Unicode characters and returns a UTF-8 string. Astral planes are supported i.e. the ints in the input can be > 0xFFFF. Occurrances of the BOM are ignored. Surrogates are not allowed.
$str = UTF8::to_unicode($array);
The Original Code is Mozilla Communicator client code. The Initial Developer of the Original Code is Netscape Communications Corporation. Portions created by the Initial Developer are Copyright (C) 1998 the Initial Developer. Ported to PHP by Henri Sivonen hsivonen@iki.fi, see http://hsivonen.iki.fi/php-utf8/ Slight modifications to fit with phputf8 library by Harry Fuecks hfuecks@gmail.com.
Tests whether a string contains only 7-bit ASCII bytes. This is used to determine when to use native functions or UTF-8 functions.
$ascii = UTF8::is_ascii($str);
Strips whitespace (or other UTF-8 characters) from the beginning of a string. This is a UTF8-aware version of ltrim.
$str = UTF8::ltrim($str);
Returns the unicode ordinal for a character. This is a UTF8-aware version of ord.
$digit = UTF8::ord($character);
Strips whitespace (or other UTF-8 characters) from the end of a string. This is a UTF8-aware version of rtrim.
$str = UTF8::rtrim($str);
Returns a string or an array with all occurrences of search in subject (ignoring case) and replaced with the given replace value. This is a UTF8-aware version of str_ireplace.
This function is very slow compared to the native version. Avoid using it when possible.
Pads a UTF-8 string to a certain length with another string. This is a UTF8-aware version of str_pad.
$str = UTF8::str_pad($str, $length);
Converts a UTF-8 string to an array. This is a UTF8-aware version of str_split.
$array = UTF8::str_split($str);
Case-insensitive UTF-8 string comparison. This is a UTF8-aware version of strcasecmp.
$compare = UTF8::strcasecmp($str1, $str2);
Finds the length of the initial segment not matching mask. This is a UTF8-aware version of strcspn.
$found = UTF8::strcspn($str, $mask);
Strips out device control codes in the ASCII range.
$str = UTF8::strip_ascii_ctrl($str);
Strips out all non-7bit ASCII bytes.
$str = UTF8::strip_non_ascii($str);
Case-insenstive UTF-8 version of strstr. Returns all of input string from the first occurrence of needle to the end. This is a UTF8-aware version of stristr.
$found = UTF8::stristr($str, $search);
Returns the length of the given string. This is a UTF8-aware version of strlen.
$length = UTF8::strlen($str);
Finds position of first occurrence of a UTF-8 string. This is a UTF8-aware version of strpos.
$position = UTF8::strpos($str, $search);
Reverses a UTF-8 string. This is a UTF8-aware version of strrev.
$str = UTF8::strrev($str);
Finds position of last occurrence of a char in a UTF-8 string. This is a UTF8-aware version of strrpos.
$position = UTF8::strrpos($str, $search);
Finds the length of the initial segment matching mask. This is a UTF8-aware version of strspn.
$found = UTF8::strspn($str, $mask);
Makes a UTF-8 string lowercase. This is a UTF8-aware version of strtolower.
$str = UTF8::strtolower($str);
Makes a UTF-8 string uppercase. This is a UTF8-aware version of strtoupper.
Returns part of a UTF-8 string. This is a UTF8-aware version of substr.
$sub = UTF8::substr($str, $offset);
Replaces text within a portion of a UTF-8 string. This is a UTF8-aware version of substr_replace.
$str = UTF8::substr_replace($str, $replacement, $offset);
Takes an UTF-8 string and returns an array of ints representing the Unicode characters. Astral planes are supported i.e. the ints in the output can be > 0xFFFF. Occurrences of the BOM are ignored. Surrogates are not allowed.
$array = UTF8::to_unicode($str);
The Original Code is Mozilla Communicator client code. The Initial Developer of the Original Code is Netscape Communications Corporation. Portions created by the Initial Developer are Copyright (C) 1998 the Initial Developer. Ported to PHP by Henri Sivonen hsivonen@iki.fi, see http://hsivonen.iki.fi/php-utf8/ Slight modifications to fit with phputf8 library by Harry Fuecks hfuecks@gmail.com
Replaces special/accented UTF-8 characters by ASCII-7 "equivalents".
$ascii = UTF8::transliterate_to_ascii($utf8);
Strips whitespace (or other UTF-8 characters) from the beginning and end of a string. This is a UTF8-aware version of trim.
$str = UTF8::trim($str);
Makes a UTF-8 string's first character uppercase. This is a UTF8-aware version of ucfirst.
$str = UTF8::ucfirst($str);
Makes the first character of every word in a UTF-8 string uppercase. This is a UTF8-aware version of ucwords.
$str = UTF8::ucwords($str);
Array and variable validation.
Checks whether a string consists of alphabetical characters only.
Checks whether a string consists of alphabetical characters, numbers, underscores and dashes only.
Checks whether a string consists of alphabetical characters and numbers only.
Returns the array representation of the current object.
Adds a callback to a field. Each callback will be executed only once.
// The "username" must be checked with a custom method
$validation->callback('username', array($this, 'check_username'));
To add a callback to every field already set, use TRUE for the field name.
Add callbacks using an array.
Executes all validation filters, rules, and callbacks. This should typically be called within an if/else block.
if ($validation->check())
{
// The data is valid, do something here
}
Checks if a string is a proper hexadecimal HTML color value. The validation is quite flexible as it does not require an initial "#" and also allows for the short notation using only three instead of six hexadecimal characters.
Copies the current filter/rule/callback to a new array.
$copy = $array->copy($new_data);
Validates a credit card number, with a Luhn check if possible.
Tests if a string is a valid date string.
Checks if a string is a proper decimal format. Optionally, a specific number of digits can be checked too.
Checks whether a string consists of digits only (no dots or dashes).
Check an email address for correct format.
Validate the domain of an email address by checking if the domain has a valid MX record.
Checks that a field is exactly the value required.
Add an error to a field.
Returns the error messages. If no file is specified, the error message
will be the name of the rule that failed. When a file is specified, the
message will be loaded from $field.$rule, or if no rule-specific message
exists, $field.default will be used. If neither is set, the returned
message will be validate.$rule. If validate.$rule is empty,
then $file.$field.$rule will be returned.
By default all messages are translated using the default language. A string can be used as the second parameter to specified the language that the message was written in.
// Get errors from messages/forms/login.php
$errors = $validate->errors('forms/login');
Checks that a field is exactly the right length.
Creates a new Validation instance.
Overwrites or appends filters to a field. Each filter will be executed once. All rules must be valid PHP callbacks.
// Run trim() on all fields
$validation->filter(TRUE, 'trim');
Add filters using an array.
Validate an IP.
Sets or overwrites the label name for a field.
Sets labels using an array.
Checks that a field is short enough.
Checks that a field is long enough.
Checks if a field is not empty.
Checks whether a string is a valid number (negative and decimal numbers allowed).
Uses {@link http://www.php.net/manual/en/function.localeconv.php locale conversion} to allow decimal point to be locale specific.
Checks if a phone number is valid.
Tests if a number is within a range.
Checks a field against a regular expression.
Overwrites or appends rules to a field. Each rule will be executed once. All rules must be string names of functions method names.
// The "username" must not be empty and have a minimum length of 4
$validation->rule('username', 'not_empty')
->rule('username', 'min_length', array(4));
Add rules using an array.
Validate a URL.
Checks if a field matches the value of another field.
Acts as an object wrapper for HTML pages with embedded PHP, called "views". Variables can be assigned with the view object and referenced locally within the view.
Assigns a value by reference. The benefit of binding is that values can be altered without re-setting them. It is also possible to bind variables before they have values. Assigned values will be available as a variable within the view file:
// This reference can be accessed as $ref within the view
$view->bind('ref', $bar);
Assigns a global variable by reference, similar to View::bind, except that the variable will be accessible to all views.
View::bind_global($key, $value);
Returns a new View object. If you do not define the "file" parameter, you must call View::set_filename.
$view = View::factory($file);
Renders the view object to a string. Global and local data are merged and extracted to create local variables within the view file.
$output = $view->render();
Global variables with the same key name as local variables will be overwritten by the local variable.
Assigns a variable by name. Assigned values will be available as a variable within the view file:
// This value can be accessed as $foo within the view
$view->set('foo', 'my value');
You can also use an array to set several values at once:
// Create the values $food and $beverage in the view
$view->set(array('food' => 'bread', 'beverage' => 'water'));
Sets the view filename.
$view->set_filename($file);
Sets a global variable, similar to View::set, except that the variable will be accessible to all views.
View::set_global($name, $value);
Captures the output that is generated when a view is included. The view data will be extracted to make local variables. This method is static to prevent object scope resolution.
$output = View::capture($file, $data);