Common.php
This file is part of the CodeIgniter 4 framework.
(c) CodeIgniter Foundation admin@codeigniter.com
For the full copyright and license information, please view the LICENSE file that was distributed with this source code.
Table of Contents
- app_timezone() : string
- Returns the timezone the application has been set to display dates in. This might be different than the timezone set at the server level, as you often want to stores dates in UTC and convert them on the fly for the user.
- cache() : CacheInterface|mixed
- A convenience method that provides access to the Cache object. If no parameter is provided, will return the object, otherwise, will attempt to return the cached value.
- clean_path() : string
- A convenience method to clean paths for a nicer looking output. Useful for exception handling, error logging, etc.
- command() : false|string
- Runs a single command.
- config() : mixed
- More simple way of getting config instances from Factories
- cookie() : Cookie
- Simpler way to create a new Cookie instance.
- cookies() : CookieStore
- Fetches the global `CookieStore` instance held by `Response`.
- csrf_token() : string
- Returns the CSRF token name.
- csrf_header() : string
- Returns the CSRF header name.
- csrf_hash() : string
- Returns the current hash value for the CSRF protection.
- csrf_field() : string
- Generates a hidden input field for use within manually generated forms.
- csrf_meta() : string
- Generates a meta tag for use within javascript calls.
- db_connect() : BaseConnection
- Grabs a database connection and returns it to the user.
- dd() : mixed
- Prints a Kint debug report and exits.
- env() : mixed
- Allows user to retrieve values from the environment variables that have been set. Especially useful for retrieving values set from the .env file for use in config files.
- esc() : string|array<string|int, mixed>
- Performs simple auto-escaping of data for security reasons.
- force_https() : mixed
- Used to force a page to be accessed in via HTTPS.
- function_usable() : bool
- Function usable
- helper() : mixed
- Loads a helper file into memory. Supports namespaced helpers, both in and out of the 'helpers' directory of a namespaced directory.
- is_cli() : bool
- Check if PHP was invoked from the command line.
- is_really_writable() : bool
- Tests for file writability
- lang() : string
- A convenience method to translate a string or array of them and format the result with the intl extension's MessageFormatter.
- log_message() : mixed
- A convenience/compatibility method for logging events through the Log system.
- model() : mixed
- More simple way of getting model instances from Factories
- old() : mixed|null
- Provides access to "old input" that was set in the session during a redirect()->withInput().
- redirect() : RedirectResponse
- Convenience method that works with the current global $request and $router instances to redirect using named/reverse-routed routes to determine the URL to go to. If nothing is found, will treat as a traditional redirect and pass the string in, letting $response->redirect() determine the correct method and code.
- remove_invisible_characters() : string
- Remove Invisible Characters
- route_to() : false|string
- Given a controller/method string and any params, will attempt to build the relative URL to the matching route.
- session() : Session|mixed|null
- A convenience method for accessing the session instance, or an item that has been set in the session.
- service() : mixed
- Allows cleaner access to the Services Config file.
- single_service() : mixed
- Always returns a new instance of the class.
- slash_item() : string|null
- Fetch a config file item with slash appended (if not empty)
- stringify_attributes() : string
- Stringify attributes for use in HTML tags.
- timer() : Timer|mixed
- A convenience method for working with the timer.
- trace() : mixed
- Provides a backtrace to the current execution point, from Kint.
- view() : string
- Grabs the current RendererInterface-compatible class and tells it to render the specified view. Simply provides a convenience method that can be used in Controllers, libraries, and routed closures.
- view_cell() : string
- View cells are used within views to insert HTML chunks that are managed by other classes.
- class_basename() : string
- Get the class "basename" of the given object / class.
- class_uses_recursive() : array<string|int, mixed>
- Returns all traits used by a class, its parent classes and trait of their traits.
- trait_uses_recursive() : array<string|int, mixed>
- Returns all traits used by a trait and its traits.
Functions
app_timezone()
Returns the timezone the application has been set to display dates in. This might be different than the timezone set at the server level, as you often want to stores dates in UTC and convert them on the fly for the user.
app_timezone() : string
Return values
string —cache()
A convenience method that provides access to the Cache object. If no parameter is provided, will return the object, otherwise, will attempt to return the cached value.
cache([string|null $key = null ]) : CacheInterface|mixed
Examples: cache()->save('foo', 'bar'); $foo = cache('bar');
Parameters
- $key : string|null = null
Return values
CacheInterface|mixed —clean_path()
A convenience method to clean paths for a nicer looking output. Useful for exception handling, error logging, etc.
clean_path(string $path) : string
Parameters
- $path : string
Return values
string —command()
Runs a single command.
command(string $command) : false|string
Input expected in a single string as would be used on the command line itself:
command('migrate:create SomeMigration');
Parameters
- $command : string
Return values
false|string —config()
More simple way of getting config instances from Factories
config(string $name[, bool $getShared = true ]) : mixed
Parameters
- $name : string
- $getShared : bool = true
Return values
mixed —cookie()
Simpler way to create a new Cookie instance.
cookie(string $name[, string $value = '' ][, array<string|int, mixed> $options = [] ]) : Cookie
Parameters
- $name : string
-
Name of the cookie
- $value : string = ''
-
Value of the cookie
- $options : array<string|int, mixed> = []
-
Array of options to be passed to the cookie
Tags
Return values
Cookie —cookies()
Fetches the global `CookieStore` instance held by `Response`.
cookies([array<string|int, Cookie> $cookies = [] ][, bool $getGlobal = true ]) : CookieStore
Parameters
- $cookies : array<string|int, Cookie> = []
-
If
getGlobal
is false, this is passed to CookieStore's constructor - $getGlobal : bool = true
-
If false, creates a new instance of CookieStore
Return values
CookieStore —csrf_token()
Returns the CSRF token name.
csrf_token() : string
Can be used in Views when building hidden inputs manually, or used in javascript vars when using APIs.
Return values
string —csrf_header()
Returns the CSRF header name.
csrf_header() : string
Can be used in Views by adding it to the meta tag or used in javascript to define a header name when using APIs.
Return values
string —csrf_hash()
Returns the current hash value for the CSRF protection.
csrf_hash() : string
Can be used in Views when building hidden inputs manually, or used in javascript vars for API usage.
Return values
string —csrf_field()
Generates a hidden input field for use within manually generated forms.
csrf_field([string|null $id = null ]) : string
Parameters
- $id : string|null = null
Return values
string —csrf_meta()
Generates a meta tag for use within javascript calls.
csrf_meta([string|null $id = null ]) : string
Parameters
- $id : string|null = null
Return values
string —db_connect()
Grabs a database connection and returns it to the user.
db_connect([ConnectionInterface|array<string|int, mixed>|string|null $db = null ][, bool $getShared = true ]) : BaseConnection
This is a convenience wrapper for \Config\Database::connect() and supports the same parameters. Namely:
When passing in $db, you may pass any of the following to connect:
- group name
- existing connection instance
- array of database configuration values
If $getShared === false then a new connection instance will be provided, otherwise it will all calls will return the same instance.
Parameters
- $db : ConnectionInterface|array<string|int, mixed>|string|null = null
- $getShared : bool = true
Return values
BaseConnection —dd()
Prints a Kint debug report and exits.
dd(array<string|int, mixed> ...$vars) : mixed
Parameters
- $vars : array<string|int, mixed>
Tags
Return values
mixed —env()
Allows user to retrieve values from the environment variables that have been set. Especially useful for retrieving values set from the .env file for use in config files.
env(string $key[, string|null $default = null ]) : mixed
Parameters
- $key : string
- $default : string|null = null
Return values
mixed —esc()
Performs simple auto-escaping of data for security reasons.
esc(string|array<string|int, mixed> $data[, string $context = 'html' ][, string $encoding = null ]) : string|array<string|int, mixed>
Might consider making this more complex at a later date.
If $data is a string, then it simply escapes and returns it. If $data is an array, then it loops over it, escaping each 'value' of the key/value pairs.
Valid context values: html, js, css, url, attr, raw, null
Parameters
- $data : string|array<string|int, mixed>
- $context : string = 'html'
- $encoding : string = null
Tags
Return values
string|array<string|int, mixed> —force_https()
Used to force a page to be accessed in via HTTPS.
force_https([int $duration = 31536000 ][, RequestInterface $request = null ][, ResponseInterface $response = null ]) : mixed
Uses a standard redirect, plus will set the HSTS header for modern browsers that support, which gives best protection against man-in-the-middle attacks.
Parameters
- $duration : int = 31536000
-
How long should the SSL header be set for? (in seconds) Defaults to 1 year.
- $request : RequestInterface = null
- $response : ResponseInterface = null
Tags
Return values
mixed —function_usable()
Function usable
function_usable(string $functionName) : bool
Executes a function_exists() check, and if the Suhosin PHP extension is loaded - checks whether the function that is checked might be disabled in there as well.
This is useful as function_exists() will return FALSE for functions disabled via the disable_functions php.ini setting, but not for suhosin.executor.func.blacklist and suhosin.executor.disable_eval. These settings will just terminate script execution if a disabled function is executed.
The above described behavior turned out to be a bug in Suhosin, but even though a fix was committed for 0.9.34 on 2012-02-12, that version is yet to be released. This function will therefore be just temporary, but would probably be kept for a few years.
Parameters
- $functionName : string
-
Function to check for
Tags
Return values
bool —TRUE if the function exists and is safe to call, FALSE otherwise.
helper()
Loads a helper file into memory. Supports namespaced helpers, both in and out of the 'helpers' directory of a namespaced directory.
helper(string|array<string|int, mixed> $filenames) : mixed
Will load ALL helpers of the matching name, in the following order:
- app/Helpers
- {namespace}/Helpers
- system/Helpers
Parameters
- $filenames : string|array<string|int, mixed>
Tags
Return values
mixed —is_cli()
Check if PHP was invoked from the command line.
is_cli() : bool
Tags
Return values
bool —is_really_writable()
Tests for file writability
is_really_writable(string $file) : bool
is_writable() returns TRUE on Windows servers when you really can't write to the file, based on the read-only attribute. is_writable() is also unreliable on Unix servers if safe_mode is on.
Parameters
- $file : string
Tags
Return values
bool —lang()
A convenience method to translate a string or array of them and format the result with the intl extension's MessageFormatter.
lang(string $line[, array<string|int, mixed> $args = [] ][, string|null $locale = null ]) : string
Parameters
- $line : string
- $args : array<string|int, mixed> = []
- $locale : string|null = null
Return values
string —log_message()
A convenience/compatibility method for logging events through the Log system.
log_message(string $level, string $message[, array<string|int, mixed> $context = [] ]) : mixed
Allowed log levels are:
- emergency
- alert
- critical
- error
- warning
- notice
- info
- debug
Parameters
- $level : string
- $message : string
- $context : array<string|int, mixed> = []
Return values
mixed —model()
More simple way of getting model instances from Factories
model(string $name[, bool $getShared = true ][, ConnectionInterface|null &$conn = null ]) : mixed
Parameters
- $name : string
- $getShared : bool = true
- $conn : ConnectionInterface|null = null
Return values
mixed —old()
Provides access to "old input" that was set in the session during a redirect()->withInput().
old(string $key[, null $default = null ][, string|bool $escape = 'html' ]) : mixed|null
Parameters
- $key : string
- $default : null = null
- $escape : string|bool = 'html'
Return values
mixed|null —redirect()
Convenience method that works with the current global $request and $router instances to redirect using named/reverse-routed routes to determine the URL to go to. If nothing is found, will treat as a traditional redirect and pass the string in, letting $response->redirect() determine the correct method and code.
redirect([string $route = null ]) : RedirectResponse
If more control is needed, you must use $response->redirect explicitly.
Parameters
- $route : string = null
Return values
RedirectResponse —remove_invisible_characters()
Remove Invisible Characters
remove_invisible_characters(string $str[, bool $urlEncoded = true ]) : string
This prevents sandwiching null characters between ascii characters, like Java\0script.
Parameters
- $str : string
- $urlEncoded : bool = true
Return values
string —route_to()
Given a controller/method string and any params, will attempt to build the relative URL to the matching route.
route_to(string $method, mixed ...$params) : false|string
NOTE: This requires the controller/method to have a route defined in the routes Config file.
Parameters
- $method : string
- $params : mixed
Return values
false|string —session()
A convenience method for accessing the session instance, or an item that has been set in the session.
session([string $val = null ]) : Session|mixed|null
Examples: session()->set('foo', 'bar'); $foo = session('bar');
Parameters
- $val : string = null
Return values
Session|mixed|null —service()
Allows cleaner access to the Services Config file.
service(string $name, mixed ...$params) : mixed
Always returns a SHARED instance of the class, so calling the function multiple times should always return the same instance.
These are equal:
- $timer = service('timer')
- $timer = \CodeIgniter\Config\Services::timer();
Parameters
- $name : string
- $params : mixed
Return values
mixed —single_service()
Always returns a new instance of the class.
single_service(string $name, mixed ...$params) : mixed
Parameters
- $name : string
- $params : mixed
Return values
mixed —slash_item()
Fetch a config file item with slash appended (if not empty)
slash_item(string $item) : string|null
Parameters
- $item : string
-
Config item name
Return values
string|null —The configuration item or NULL if the item doesn't exist
stringify_attributes()
Stringify attributes for use in HTML tags.
stringify_attributes(mixed $attributes[, bool $js = false ]) : string
Helper function used to convert a string, array, or object of attributes to a string.
Parameters
- $attributes : mixed
-
string, array, object
- $js : bool = false
Return values
string —timer()
A convenience method for working with the timer.
timer([string|null $name = null ]) : Timer|mixed
If no parameter is passed, it will return the timer instance, otherwise will start or stop the timer intelligently.
Parameters
- $name : string|null = null
Return values
Timer|mixed —trace()
Provides a backtrace to the current execution point, from Kint.
trace() : mixed
Return values
mixed —view()
Grabs the current RendererInterface-compatible class and tells it to render the specified view. Simply provides a convenience method that can be used in Controllers, libraries, and routed closures.
view(string $name[, array<string|int, mixed> $data = [] ][, array<string|int, mixed> $options = [] ]) : string
NOTE: Does not provide any escaping of the data, so that must all be handled manually by the developer.
Parameters
- $name : string
- $data : array<string|int, mixed> = []
- $options : array<string|int, mixed> = []
-
Unused - reserved for third-party extensions.
Return values
string —view_cell()
View cells are used within views to insert HTML chunks that are managed by other classes.
view_cell(string $library[, null $params = null ], int $ttl[, string|null $cacheName = null ]) : string
Parameters
- $library : string
- $params : null = null
- $ttl : int
- $cacheName : string|null = null
Tags
Return values
string —class_basename()
Get the class "basename" of the given object / class.
class_basename(string|object $class) : string
Parameters
- $class : string|object
Tags
Return values
string —class_uses_recursive()
Returns all traits used by a class, its parent classes and trait of their traits.
class_uses_recursive(object|string $class) : array<string|int, mixed>
Parameters
- $class : object|string
Tags
Return values
array<string|int, mixed> —trait_uses_recursive()
Returns all traits used by a trait and its traits.
trait_uses_recursive(string $trait) : array<string|int, mixed>
Parameters
- $trait : string