Environment configuration in Codeception with dotenv

Codeception is configurated using the codeception.yml file. But, you don't want to store any credentials in this file. You can use a dotenv configuration file to store these data (for example database credentials) and use them in our code and codeception.yml file.


Head over to the phpdotenv repository to learn more about dotenv configuration and why you should use it.

Set up .env

First, create a .env.example file in the root of your repository. Fill it with all the names of variables that you need, but do not fill in the actual data:


Then, copy .env.example to .env and set all the variables to their correct values:


Add the example file to Git. Add .env to your .gitignore list, never add it to your repository.

Configure Codeception

This is the codeception.yml that I've used for a recent project:

actor: Tester
    tests: tests
    log: tests/_output
    data: tests/_data
    support: tests/_support
    envs: tests/_envs
    bootstrap: _bootstrap.php
    colors: true
    memory_limit: 1024M
        - Codeception\Extension\RunFailed
            dsn: "mysql:host=%DB_HOST%:%DB_PORT%;dbname=%DB_DATABASE%"
            user: "%DB_USERNAME%"
            password: "%DB_PASSWORD%"
    - .env

As you can see the last line instructs Codeception to load the .env file and read all variables that it contains.

You can use these variables in your configuration like you see in the database configuration parts. %DB_HOST% with be replaced with the value of DB_HOST from .env.

Using variables in your code

All variables will be assigned to the global $_ENV variable. So, in your PHP code, you can read from $_ENV['DB_HOST'] to retrieve the same value as before.

If you have any questions or comments about this post, feel free to leave a comment!

Related articles

Comments (4)

Got a question? Liked the article or got a suggestion? Leave a comment to let us know.

When I try this, I get the following error:

Failed loading params from .env
`vlucas/phpdotenv` library is required to parse .env files.
Please install it via composer: composer require vlucas/phpdotenv

I have it installed and it is in my compsoser.json file. Any tips?
Hi Steve,

Sorry, I'm not sure what is causing that exception. You could take a look at this project where I used this set: https://github.com/barryvanveen/allunited-import-news.

Hope that helps!

Thanks for posting, this is exactly what I needed.

However, perhaps a more cleaner way of reading the $_ENV values is with getenv(), for example getenv('DB_HOST').
Thanks for this useful article

@Steve Is your .env loaded in your test class ? Like :

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);

@Edwin I've seen here https://github.com/vlucas/phpdotenv#putenv-and-getenv that getenv() is not recommanded