Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP getenv always returns false

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.

use Symfony\Component\Dotenv\Dotenv;
use Symfony\Component\Dotenv\Exception\PathException;

if (!getenv('APP_ENV')) {
    try {
        (new Dotenv())->load(__DIR__ . '/../.env');
    } catch (PathException $ex) {
        echo $ex->getMessage();
        exit(1);
    }
}

var_dump(getenv('APP_ENV')); // bool(false)

But when I dump the super global I can see my variables

var_dump($_ENV); // array:1["APP_ENV" => "dev"]

So what am I missing?

like image 796
Andrew Avatar asked Jul 10 '26 02:07

Andrew


1 Answers

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

like image 100
Ismail Bouaddi Avatar answered Jul 11 '26 21:07

Ismail Bouaddi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!