I'm new to slim framework. I'd try to add .env file in root folder project and then I want to access the value inside .env file. I've tried use this package https://github.com/vlucas/phpdotenv and load .env in index.php. But when I tried to get the value in .env file use like ex: getenv("DB_NAME") it returns false. Not return string value of DB_NAME.
.env
DB_HOST = localhost
DB_PORT = 3306
DB_NAME = DB
DB_USER = root
DB_PASSWORD =
index.php
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
I use slim framework ^4.*, web server laravel valet, database MySQL. Or is there any other alternative way to configure .env in slim framework ? Thank You.
From package readme file:
Using getenv() and putenv() is strongly discouraged due to the fact that these functions are not thread safe, however it is still possible to instruct PHP dotenv to use these functions. Instead of calling
Dotenv::createImmutable
, one can callDotenv::createUnsafeImmutable
, which will add the PutenvAdapter behind the scenes. Your environment variables will now be available using the getenv method, as well as the super-globals.
So the main method of getting these values is using $_ENV
and $_SERVER
super-global not getenv()
function.
You should either try to retrieve the values like:
$db_name = $_ENV['DB_NAME'];
or load the .env file like the example provided in the package:
$dotenv = Dotenv\Dotenv::createUnsafeImmutable(__DIR__);
$dotenv->load();
Also, make sure you pass correct directory (the one that .env file resides in) as the parameter. That normally should not be in the same directory as index.php but the example code you provide implies you are putting both files in one directory.