Configuration and the .env file
Settings are the values the site depends on: its address, language, database access. In CodeIgniter they are stored in classes in the app/Config folder, one class per subject. Values that differ between your computer and the server are overridden in the .env file.
Config files
| File | What it configures |
|---|---|
app/Config/App.php | The site address, language, time zone |
app/Config/Database.php | The database connection |
app/Config/Routes.php | Routes |
app/Config/Filters.php | Request filters |
app/Config/Session.php | Sessions |
app/Config/Email.php | Sending email |
Each setting is a public property of the class with a comment above it.
Reading a setting
The config() function returns the config object:
// app/Controllers/Home.php
public function index(): string
{
return 'Site address: ' . config('App')->baseURL;
}The home page shows "Site address: http://localhost:8080/". The argument is the name of a class from app/Config.
Your own config file
Your own values — the number of posts per page, the blog name — are best kept in a separate class:
php spark make:config BlogThe command creates the file app/Config/Blog.php. Add properties to it:
// app/Config/Blog.php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Blog extends BaseConfig
{
public string $name = 'My blog';
public int $perPage = 10;
}Now the value is available anywhere in the project as config('Blog')->perPage.
Overriding in .env
A line in .env replaces the value of a property. The line name is the class name in lowercase, a dot, and the property name:
CI_ENVIRONMENT = development
app.baseURL = 'http://localhost:8080/'
blog.perPage = 5The file app/Config/Blog.php itself does not change, but config('Blog')->perPage returns 5. This way the same code works with different values on different computers.
Environments
The CI_ENVIRONMENT line sets the environment:
| Environment | When it is used |
|---|---|
development | On your own computer: detailed errors, the debug toolbar |
testing | When automated tests run |
production | On the live server: errors are hidden from visitors |
If the line is missing, production applies. The php spark env command prints the current environment; in code it is available as the ENVIRONMENT constant.
Common mistake
The .env file contains passwords and must not get into the repository: in a new project it is already listed in .gitignore. Because of that it does not exist on the server — after the project is moved, the file is created there by hand. Do not write passwords in the app/Config classes: those files are stored with the code and visible to everyone with access to the repository.