Table of Contents
Inside this article we will see how to create environment variables in CodeIgniter 4. This article contains classified information about adding environment variables in CodeIgniter.
Environment variables define inside .env file. These variables are also known as global constants of application. Variables will be used through out application.
In .env file we configure several configuration like Email, Database, Security, etc. We can use these or also we can create our own custom too.
Learn More –
- Global Constants in CodeIgniter 4 Tutorial
- How To Define Global Constant in CodeIgniter 4 Tutorial
- How Throttler and Rate limiting work in Codeigniter 4
- How to Create CodeIgniter 4 Custom Library?
Let’s get started.
What is env?
env stands for Environment. It contains environment variables which we can use within entire application. By default we get env. But to use or access variables from it we need to do it as .env.
We get this env file at application root.
We have two options to do it as .env:
- Rename env to .env
- Copy file and rename it.
CodeIgniter 4 Installation
To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.
$ composer create-project codeigniter4/appstarter codeigniter-4
Assuming you have successfully installed application into your local system.
Create Environment Variables
To define user defined variables there is very simple process to create. Open .env file and add your custom variables like this –
//... MY_FIRST_VARIABLE="This is first sample environment variable" MY_SECOND_VARIABLE="Second environment variable for application" //...
When your application runs, .env will be loaded automatically, and the variables put into the environment. If a variable already exists in the environment, it will NOT be overwritten.
Successfully, we can see we have added our own custom environment variables into .env file.
How To Use?
To access and use the value of environment variables we have few helper functions available by CodeIgniter 4.
We can use these function to any controller, any view to access value of it.
Available helper functions are –
To access value of an environment variable, code be like this –
We hope this article helped you to learn How To Create Environment Variables in CodeIgniter 4 Tutorial in a very detailed way.
Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.