Global Functions and Constants

CodeIgniter uses provides a few functions and variables that are globally defined, and are available to you at any point.These do not require loading any additional libraries or helpers.

Global Functions

Service Accessors

  • cache([$key])

Parameters:

  • $key (string) – The cache name of the item to retrieve from cache (Optional)Returns:Either the cache object, or the item retrieved from the cacheReturn type:mixed

If no $key is provided, will return the Cache engine instance. If a $keyis provided, will return the value of $key as stored in the cache currently,or null if no value is found.

Examples:

  1. $foo = cache('foo');
  2. $cache = cache();
  • env($key[, $default=null])

Parameters:

  • $key (string) – The name of the environment variable to retrieve
  • $default (mixed) – The default value to return if no value is found.Returns:The environment variable, the default value, or null.Return type:mixed

Used to retrieve values that have previously been set to the environment,or return a default value if it is not found. Will format boolean valuesto actual booleans instead of string representations.

Especially useful when used in conjunction with .env files for settingvalues that are specific to the environment itself, like databasesettings, API keys, etc.

  • esc($data, $context='html'[, $encoding])

Parameters:

  • $data (string|array) – The information to be escaped.
  • $context (string) – The escaping context. Default is ‘html’.
  • $encoding (string) – The character encoding of the string.Returns:The escaped data.Return type:mixed

Escapes data for inclusion in web pages, to help prevent XSS attacks.This uses the Laminas Escaper library to handle the actual filtering of the data.

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

  • helper($filename)

Parameters:

  • $filename (string|array) – The name of the helper file to load, or an array of names.

Loads a helper file.

For full details, see the Helper Functions page.

  • lang($line[, $args[, $locale]])

Parameters:

  • $line (string) – The line of text to retrieve
  • $args (array) – An array of data to substitute for placeholders.
  • $locale (string) – Specify a different locale to be used instead of default one.

Retrieves a locale-specific file based on an alias string.

For more information, see the Localization page.

  • old($key[, $default = null[, $escape = 'html']])

Parameters:

  • $key (string) – The name of the old form data to check for.
  • $default (mixed) – The default value to return if $key doesn’t exist.
  • $escape (mixed) – An escape context or false to disable it.Returns:The value of the defined key, or the default value.Return type:mixed

Provides a simple way to access “old input data” from submitting a form.

Example:

  1. // in controller, checking form submittal
  2. if (! $model->save($user))
  3. {
  4. // 'withInput' is what specifies "old data"
  5. // should be saved.
  6. return redirect()->back()->withInput();
  7. }
  8.  
  9. // In the view
  10. <input type="email" name="email" value="<?= old('email') ?>">
  11. // Or with arrays
  12. <input type="email" name="user[email]" value="<?= old('user.email') ?>">

Note

If you are using the form helper, this feature is built-in. You onlyneed to use this function when not using the form helper.

  • session([$key])

Parameters:

  • $key (string) – The name of the session item to check for.Returns:An instance of the Session object if no $key, the value found in the session for $key, or null.Return type:mixed

Provides a convenient way to access the session class and to retrieve astored value. For more information, see the Sessions page.

  • timer([$name])

Parameters:

  • $name (string) – The name of the benchmark point.Returns:The Timer instanceReturn type:CodeIgniterDebugTimer

A convenience method that provides quick access to the Timer class. You can pass in the nameof a benchmark point as the only parameter. This will start timing from this point, or stoptiming if a timer with this name is already running.

Example:

  1. // Get an instance
  2. $timer = timer();
  3.  
  4. // Set timer start and stop points
  5. timer('controller_loading'); // Will start the timer
  6. . . .
  7. timer('controller_loading'); // Will stop the running timer
  • view($name[, $data[, $options]])

Parameters:

  • $name (string) – The name of the file to load
  • $data (array) – An array of key/value pairs to make available within the view.
  • $options (array) – An array of options that will be passed to the rendering class.Returns:The output from the view.Return type:string

Grabs the current RendererInterface-compatible classand tells it to render the specified view. Simply providesa convenience method that can be used in Controllers,libraries, and routed closures.

Currently, only one option is available for use within the $options array, saveData which specifiesthat data will persistent between multiple calls to view() within the same request. By default, thedata for that view is forgotten after displaying that single view file.

The $option array is provided primarily to facilitate third-party integrations withlibraries like Twig.

Example:

  1. $data = ['user' => $user];
  2.  
  3. echo view('user_profile', $data);

For more details, see the Views page.

Miscellaneous Functions

  • csrf_token()

Returns:The name of the current CSRF token.Return type:string

Returns the name of the current CSRF token.

  • csrf_header()

Returns:The name of the header for current CSRF token.Return type:string

The name of the header for current CSRF token.

  • csrf_hash()

Returns:The current value of the CSRF hash.Return type:string

Returns the current CSRF hash value.

  • csrf_field()

Returns:A string with the HTML for hidden input with all required CSRF information.Return type:string

Returns a hidden input with the CSRF information already inserted:

<input type=”hidden” name=”{csrf_token}” value=”{csrf_hash}”>
  • csrf_meta()

Returns:A string with the HTML for meta tag with all required CSRF information.Return type:string

Returns a meta tag with the CSRF information already inserted:

<meta name=”{csrf_header}” content=”{csrf_hash}”>
  • forcehttps($duration = 31536000[, $request = null[, $response = null_]])

Parameters:

  • $duration (int) – The number of seconds browsers should convert links to this resource to HTTPS.
  • $request (RequestInterface) – An instance of the current Request object.
  • $response (ResponseInterface) – An instance of the current Response object.

Checks to see if the page is currently being accessed via HTTPS. If it is, thennothing happens. If it is not, then the user is redirected back to the current URIbut through HTTPS. Will set the HTTP Strict Transport Security header, which instructsmodern browsers to automatically modify any HTTP requests to HTTPS requests for the $duration.

  • is_cli()

Returns:TRUE if the script is being executed from the command line or FALSE otherwise.Return type:bool

  • logmessage($level, $message[, $context_])

Parameters:

  • $level (string) – The level of severity
  • $message (string) – The message that is to be logged.
  • $context (array) – An associative array of tags and their values that should be replaced in $messageReturns:TRUE if was logged successfully or FALSE if there was a problem logging itReturn type:bool

Logs a message using the Log Handlers defined in app/Config/Logger.php.

Level can be one of the following values: emergency, alert, critical, error, warning,notice, info, or debug.

Context can be used to substitute values in the message string. For full details, see theLogging Information page.

  • redirect(string $uri)

Parameters:

  • $uri (string) – The URI to redirect the user to.

Returns a RedirectResponse instance allowing you to easily create redirects:

  1. // Go back to the previous page
  2. return redirect()->back();
  3.  
  4. // Go to specific UI
  5. return redirect()->to('/admin');
  6.  
  7. // Go to a named/reverse-routed URI
  8. return redirect()->route('named_route');
  9.  
  10. // Keep the old input values upon redirect so they can be used by the `old()` function
  11. return redirect()->back()->withInput();
  12.  
  13. // Set a flash message
  14. return redirect()->back()->with('foo', 'message');

When passing a URI into the function, it is treated as a reverse-route request, not a relative/full URI, treatingit the same as using redirect()->route():

  1. // Go to a named/reverse-routed URI
  2. return redirect('named_route');
  • removeinvisible_characters($str[, $urlEncoded = TRUE_])

Parameters:

  • $str (string) – Input string
  • $urlEncoded (bool) – Whether to remove URL-encoded characters as wellReturns:Sanitized stringReturn type:string

This function prevents inserting NULL characters between ASCIIcharacters, like Java\0script.

Example:

  1. remove_invisible_characters('Java\\0script');
  2. // Returns: 'Javascript'
  • routeto($method[, …$params_])

Parameters:

  • $method (string) – The named route alias, or name of the controller/method to match.
  • $params (mixed) – One or more parameters to be passed to be matched in the route.

Generates a relative URI for you based on either a named route alias, or a controller::methodcombination. Will take parameters into effect, if provided.

For full details, see the URI Routing page.

  • service($name[, …$params])

Parameters:

  • $name (string) – The name of the service to load
  • $params (mixed) – One or more parameters to pass to the service method.Returns:An instance of the service class specified.Return type:mixed

Provides easy access to any of the Services defined in the system.This will always return a shared instance of the class, so no matter how many times this is calledduring a single request, only one class instance will be created.

Example:

  1. $logger = service('logger');
  2. $renderer = service('renderer', APPPATH.'views/');
  • singleservice($name[, …$params_])

Parameters:

  • $name (string) – The name of the service to load
  • $params (mixed) – One or more parameters to pass to the service method.Returns:An instance of the service class specified.Return type:mixed

Identical to the service() function described above, except that all calls to thisfunction will return a new instance of the class, where service returns the sameinstance every time.

  • stringifyattributes($attributes[, $js_])

Parameters:

  • $attributes (mixed) – string, array of key value pairs, or object
  • $js (boolean) – TRUE if values do not need quotes (Javascript-style)Returns:String containing the attribute key/value pairs, comma-separatedReturn type:string

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

Global Constants

The following constants are always available anywhere within your application.

Core Constants

  • constant APPPATH
  • The path to the app directory.
  • constant ROOTPATH
  • The path to the project root directory. Just above APPPATH.
  • constant SYSTEMPATH
  • The path to the system directory.
  • constant FCPATH
  • The path to the directory that holds the front controller.
  • constant WRITEPATH
  • The path to the writable directory.

Time Constants

  • constant SECOND
  • Equals 1.
  • constant MINUTE
  • Equals 60.
  • constant HOUR
  • Equals 3600.
  • constant DAY
  • Equals 86400.
  • constant WEEK
  • Equals 604800.
  • constant MONTH
  • Equals 2592000.
  • constant YEAR
  • Equals 31536000.
  • constant DECADE
  • Equals 315360000.