How To Create Environment Variables in CodeIgniter 4

Share this Article
Reading Time: 3 minutes
6,595 Views

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 –

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 –

  • getenv()
  • $_ENV[]
  • $_SERVER[]

Usage

To access value of an environment variable, code be like this –

echo getenv('MY_FIRST_VARIABLE');

OR

echo $_ENV['MY_FIRST_VARIABLE'];

OR

echo $_SERVER['MY_FIRST_VARIABLE'];

We hope this article helped you to learn How To Create Environment Variables in CodeIgniter 4 Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.