PHP getenv always returns false

前端 未结 2 967
死守一世寂寞
死守一世寂寞 2021-01-29 05:21

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.



        
相关标签:
2条回答
  • 2021-01-29 06:00

    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

    0 讨论(0)
  • 2021-01-29 06:08

    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 :

    • Before Symfony 5.1 : In your config/bootstrap.php file -> new Dotenv(true)
    • Symfony 5.1 and later : public/index.php, add the following before Dotenv instantation-> Dotenv::usePutenv();

    EDIT :

    • Using the putenv PHP function is not thread safe, that's why this setting defaults to false.
    • Didn't notice in the first place your using the Dotenv component as a standalone library, so you can ignore my advice concerning the dependency injection.
    0 讨论(0)
提交回复
热议问题