- Published at
CodeIgniter Simplified: Setting Up a .env File Step-by-Step
- Authors
-
-
- Name
- Fransiscus Rolanda Malau
- https://x.com/odnmalau
-
Table of Contents
It’s crucial to avoid embedding sensitive credentials directly in your code. Adhering to the principles of a twelve-factor app, one should place configuration settings in the environment. Variables likely to vary across different deployment environments, like database credentials or third-party service keys, should be moved out of the code and into environment variables.
Installation
You will need to install the vlucas/phpdotenv package to use the .env file in CodeIgniter. You can install it using Composer by running the following command:
composer require vlucas/phpdotenv
Create a .env file in the root directory of your CodeIgniter application
In the .env file, define your environment variables in the following format: VARIABLE_NAME=value. For example:
DB_HOST=localhost
DB_USERNAME=root
DB_PASSWORD=password
Load the .env file in your CodeIgniter application by adding the following line to the top of your index.php file:
$dotenv = \Dotenv\Dotenv::createImmutable(FCPATH);
$dotenv->safeLoad();
Usage
You can now access the environment variables in your CodeIgniter application like this:
$host = $_ENV['DB_HOST'];
$username = $_ENV['DB_USERNAME'];
$password = $_ENV['DB_PASSWORD'];
Security Considerations
Ensure that your .env file is properly secured and not accessible from the web. This can typically be achieved by proper server configuration and by adding .env to your .gitignore file to prevent it from being committed to version control.
Remember that this is a custom integration and might require adjustments based on the specifics of your CodeIgniter setup and server environment.
Further Reading: