'Load a .env file with PHP
I'm currently coding on a pure PHP project and I need to load an .env file to get some variables. After a bit of searching I turned to the vlucas/phpdotenv plugin (That I imported with Composer), but I can't import it! Do I have to use an MVC model for this to work?
index.php:
<?php
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
bdd.php:
<?php
function DBConnect() {
$user = getenv("DB_USER");
$pass = $_ENV["DB_PASSWORD"];
Solution 1:[1]
You forgot to add require_once realpath(__DIR__ . '/vendor/autoload.php');
to your index.php
.env
USER_NAME='jfBiswajit'
index.php
<?php
require_once realpath(__DIR__ . '/vendor/autoload.php');
// Looing for .env at the root directory
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
// Retrive env variable
$userName = $_ENV['USER_NAME'];
echo $userName; //jfBiswajit
Solution 2:[2]
v5 has changed even further; Use createUnsafeImmutable
in place of createImmutable
The Dotenv\Dotenv::createImmutable and Dotenv\Dotenv::createMutable methods no longer call will result in getenv and putenv being called. One should instead use Dotenv\Dotenv::createUnsafeImmutable and Dotenv\Dotenv::createUnsafeMutable methods, if one really needs these functions.
Here is the guide for upgrading
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Biswajit Biswas |
Solution 2 | shiv chawla |