So I am using vlucas/phpdotenv in my php application to store and use environment variables. I have created a db.php file which contains the configuration of my database connection. The folder structure is root/config/db.php.
I have require('../vendor/autoload.php');
in the db.php file and then I have used
$dotenv=Dotenv\Dotenv::createImmutable('../');
$dotenv->load();
print_r($_ENV);
to access the environment variables since the .env file is in the root of the directory. It all works perfectly fine when i access the db.php file on the server but when I include this file in the register.php file which is in the root I get the error "Fatal error: require(): Failed opening required '../vendor/autoload.php' (include_path='C:\xampp\php\PEAR')".
However when I change the directory of the autoload.php to match the path I then get this error: "Uncaught Dotenv\Exception\InvalidPathException: Unable to read any of the environment file(s) at [../.env]."
Can someone please help me out here? Thank you.
It looks like you're using a relative path, but expecting it to function like an absolute path.
the ../ notation meant the parent directory, so if you move the file the parent directory changes also.
Instead of working relatively, I prefer to set a base and work upwards.
Use $_SERVER['DOCUMENT_ROOT']
, which is the file path to the root of your application.
require($_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php');
Then use the same notation in you createImmutable
static call. I don't know where you're supposed to be pointing that to. If it's the root, use...
$dotenv=Dotenv\Dotenv::createImmutable($_SERVER['DOCUMENT_ROOT']);
$dotenv->load();
print_r($_ENV);