CodeIgniter v4.5 API

Common.php

This file is part of 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

Functions

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()  : array<string|int, mixed>|bool|CacheInterface|float|int|object|string|null
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()  : ConfigTemplate|null
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.
csp_style_nonce()  : string
Generates a nonce attribute for style tag.
csp_script_nonce()  : string
Generates a nonce attribute for script tag.
db_connect()  : BaseConnection
Grabs a database connection and returns it to the user.
env()  : bool|string|null
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()  : array<string|int, mixed>|string
Performs simple auto-escaping of data for security reasons.
force_https()  : void
Used to force a page to be accessed in via HTTPS.
function_usable()  : bool
Function usable
helper()  : void
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
is_windows()  : bool
Detect if platform is running in Windows.
lang()  : array<int, string>|string
A convenience method to translate a string or array of them and format the result with the intl extension's MessageFormatter.
log_message()  : void
A convenience/compatibility method for logging events through the Log system.
model()  : ModelTemplate|null
More simple way of getting model instances from Factories
old()  : array<string|int, mixed>|string|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.
remove_invisible_characters()  : string
Remove Invisible Characters
request()  : CLIRequest|IncomingRequest
Returns the shared Request.
response()  : ResponseInterface
Returns the shared Response.
route_to()  : false|string
Given a route name or controller/method string and any params, will attempt to build the relative URL to the matching route.
session()  : array<string|int, mixed>|bool|float|int|object|Session|string|null
A convenience method for accessing the session instance, or an item that has been set in the session.
service()  : object|null
Allows cleaner access to the Services Config file.
single_service()  : object|null
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()  : mixed|Timer
A convenience method for working with the timer.
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 ]) : array<string|int, mixed>|bool|CacheInterface|float|int|object|string|null

Examples: cache()->save('foo', 'bar'); $foo = cache('bar');

Parameters
$key : string|null = null
Tags
phpstan-return

($key is null ? CacheInterface : array|bool|float|int|object|string|null)

Return values
array<string|int, mixed>|bool|CacheInterface|float|int|object|string|null

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(ConfigTemplate>|string $name[, bool $getShared = true ]) : ConfigTemplate|null
Parameters
$name : ConfigTemplate>|string
$getShared : bool = true
Tags
template

ConfigTemplate of BaseConfig

phpstan-return

($name is class-string<ConfigTemplate> ? ConfigTemplate : object|null)

Return values
ConfigTemplate|null

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
throws
CookieException
Return values
Cookie

cookies()

Fetches the global `CookieStore` instance held by `Response`.

cookies([array<int, Cookie$cookies = [] ][, bool $getGlobal = true ]) : CookieStore
Parameters
$cookies : array<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([non-empty-string|null $id = null ]) : string
Parameters
$id : non-empty-string|null = null
Return values
string

csrf_meta()

Generates a meta tag for use within javascript calls.

csrf_meta([non-empty-string|null $id = null ]) : string
Parameters
$id : non-empty-string|null = null
Return values
string

csp_style_nonce()

Generates a nonce attribute for style tag.

csp_style_nonce() : string
Return values
string

csp_script_nonce()

Generates a nonce attribute for script tag.

csp_script_nonce() : string
Return values
string

db_connect()

Grabs a database connection and returns it to the user.

db_connect([array<string|int, mixed>|ConnectionInterface|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 : array<string|int, mixed>|ConnectionInterface|string|null = null
$getShared : bool = true
Return values
BaseConnection

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 ]) : bool|string|null
Parameters
$key : string
$default : string|null = null
Return values
bool|string|null

esc()

Performs simple auto-escaping of data for security reasons.

esc(array<string|int, mixed>|string $data[, string $context = 'html' ][, string|null $encoding = null ]) : array<string|int, mixed>|string

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.

Parameters
$data : array<string|int, mixed>|string
$context : string = 'html'
$encoding : string|null = null

Current encoding for escaping. If not UTF-8, we convert strings from this encoding pre-escaping and back to this encoding post-escaping.

Tags
phpstan-param

'html'|'js'|'css'|'url'|'attr'|'raw' $context

throws
InvalidArgumentException
Return values
array<string|int, mixed>|string

force_https()

Used to force a page to be accessed in via HTTPS.

force_https([int $duration = 31536000 ][, RequestInterface|null $request = null ][, ResponseInterface|null $response = null ]) : void

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 = null
$response : ResponseInterface|null = null
Tags
see
https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security
throws
HTTPException
throws
RedirectException

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
see
http://www.hardened-php.net/suhosin/
codeCoverageIgnore

This is too exotic

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(array<string|int, mixed>|string $filenames) : void

Will load ALL helpers of the matching name, in the following order:

  1. app/Helpers
  2. {namespace}/Helpers
  3. system/Helpers
Parameters
$filenames : array<string|int, mixed>|string
Tags
throws
FileNotFoundException

is_cli()

Check if PHP was invoked from the command line.

is_cli() : bool
Tags
codeCoverageIgnore

Cannot be tested fully as PHPUnit always run in php-cli

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
see
https://bugs.php.net/bug.php?id=54709
throws
Exception
codeCoverageIgnore

Not practical to test, as travis runs on linux

Return values
bool

is_windows()

Detect if platform is running in Windows.

is_windows([bool|null $mock = null ]) : bool
Parameters
$mock : bool|null = null
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 ]) : array<int, string>|string
Parameters
$line : string
$args : array<string|int, mixed> = []
$locale : string|null = null
Return values
array<int, string>|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 = [] ]) : void

Allowed log levels are:

  • emergency
  • alert
  • critical
  • error
  • warning
  • notice
  • info
  • debug
Parameters
$level : string
$message : string
$context : array<string|int, mixed> = []

model()

More simple way of getting model instances from Factories

model(ModelTemplate>|string $name[, bool $getShared = true ][, ConnectionInterface|null &$conn = null ]) : ModelTemplate|null
Parameters
$name : ModelTemplate>|string
$getShared : bool = true
$conn : ConnectionInterface|null = null
Tags
template

ModelTemplate of Model

phpstan-return

($name is class-string<ModelTemplate> ? ModelTemplate : object|null)

Return values
ModelTemplate|null

old()

Provides access to "old input" that was set in the session during a redirect()->withInput().

old(string $key[, string|null $default = null ][, false|string $escape = 'html' ]) : array<string|int, mixed>|string|null
Parameters
$key : string
$default : string|null = null
$escape : false|string = 'html'
Tags
phpstan-param

false|'attr'|'css'|'html'|'js'|'raw'|'url' $escape

Return values
array<string|int, mixed>|string|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.

redirect([non-empty-string|null $route = null ]) : RedirectResponse

If more control is needed, you must use $response->redirect explicitly.

Parameters
$route : non-empty-string|null = null

Route name or Controller::method

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

request()

Returns the shared Request.

request() : CLIRequest|IncomingRequest
Return values
CLIRequest|IncomingRequest

route_to()

Given a route name or controller/method string and any params, will attempt to build the relative URL to the matching route.

route_to(string $method, int|string ...$params) : false|string

NOTE: This requires the controller/method to have a route defined in the routes Config file.

Parameters
$method : string

Route name or Controller::method

$params : int|string

One or more parameters to be passed to the route. The last parameter allows you to set the locale.

Return values
false|string

The route (URI path relative to baseURL) or false if not found.

session()

A convenience method for accessing the session instance, or an item that has been set in the session.

session([string|null $val = null ]) : array<string|int, mixed>|bool|float|int|object|Session|string|null

Examples: session()->set('foo', 'bar'); $foo = session('bar');

Parameters
$val : string|null = null
Tags
phpstan-return

($val is null ? Session : array|bool|float|int|object|string|null)

Return values
array<string|int, mixed>|bool|float|int|object|Session|string|null

service()

Allows cleaner access to the Services Config file.

service(string $name, array<string|int, mixed>|bool|float|int|object|string|null ...$params) : object|null

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 : array<string|int, mixed>|bool|float|int|object|string|null
Return values
object|null

single_service()

Always returns a new instance of the class.

single_service(string $name, array<string|int, mixed>|bool|float|int|object|string|null ...$params) : object|null
Parameters
$name : string
$params : array<string|int, mixed>|bool|float|int|object|string|null
Return values
object|null

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(array<string|int, mixed>|object|string $attributes[, bool $js = false ]) : string

Helper function used to convert a string, array, or object of attributes to a string.

Parameters
$attributes : array<string|int, mixed>|object|string

string, array, object that can be cast to array

$js : bool = false
Return values
string

timer()

A convenience method for working with the timer.

timer([non-empty-string|null $name = null ][, callable(): mixed|null $callable = null ]) : mixed|Timer

If no parameter is passed, it will return the timer instance. If callable is passed, it measures time of callable and returns its return value if any. Otherwise will start or stop the timer intelligently.

Parameters
$name : non-empty-string|null = null
$callable : callable(): mixed|null = null
Tags
phpstan-return

($name is null ? Timer : ($callable is (callable(): mixed) ? mixed : Timer))

Return values
mixed|Timer

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> = []

Options for saveData or 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[, array<string|int, mixed>|string|null $params = null ][, int $ttl = 0 ][, string|null $cacheName = null ]) : string
Parameters
$library : string
$params : array<string|int, mixed>|string|null = null
$ttl : int = 0
$cacheName : string|null = null
Tags
throws
ReflectionException
Return values
string

class_basename()

Get the class "basename" of the given object / class.

class_basename(object|string $class) : string
Parameters
$class : object|string
Tags
codeCoverageIgnore
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
codeCoverageIgnore
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
Tags
codeCoverageIgnore
Return values
array<string|int, mixed>

        
On this page

Search results