The getenv()
always returns false. I am using Symfony dotenv library and loading my variables from a .env file in the root of my project.
I m not using symfony but i've encountered the some problem i am using the vlucas library this is my first code that caused the problem
define('BASE_PATH',realpath(__DIR__.'/../../'));
require_once __DIR__.'/../../vendor/autoload.php';
$dotEnv = Dotenv\Dotenv::createImmutable(BASE_PATH);
$dotEnv->load();
$appName=$_ENV['APP_NAME'];
$appName2=getenv('APP_NAME'];
var_dump($appName) // return "This is my website";
var_dump($appName2) // return false;
i didn't knwo the problem at first but it seems that it was because putenv() and getenv() are not thread safe
so i changed it to this code
define('BASE_PATH',realpath(__DIR__.'/../../'));
require_once __DIR__.'/../../vendor/autoload.php';
$dotEnv = Dotenv\Dotenv::createUnsafeImmutable(BASE_PATH);// <======== :) look here
$dotEnv->load();
$appName=$_ENV['APP_NAME'];
$appName2=getenv('APP_NAME'];
var_dump($appName) // return "This is my website";
var_dump($appName2) // return "This is my website";
i hope this resolves your issue
By default, Symfony doesn't use putenv() (I think it's for security reasons, don't remember exactly) so you are not able to use directly getenv() if you are using Symfony's "fake" environment variables.
The best solution in my opinion is to use dependency injection instead. You can access env vars in your Symfony configuration. For example with a yaml configuration file:
framework:
secret: '%env(APP_SECRET)%'
If you want to be able to use getenv() anyway, that I don't recommand for multiple reasons, you can do this :
EDIT :