@darrion.kuhn
To load data from a .env file in PHP, you can use a library like vlucas/phpdotenv. Here's a step-by-step guide on how to do it:
- Install the vlucas/phpdotenv library using Composer by running the following command in your terminal:
1
|
composer require vlucas/phpdotenv
|
- Create a .env file in the root directory of your project and add your environment variables in the following format:
1
2
3
|
DB_HOST=localhost
DB_USER=root
DB_PASS=secret
|
- Create a PHP script and require the autoload file from the vendor directory:
1
|
require 'vendor/autoload.php';
|
- Load the environment variables from the .env file using the Dotenv class:
1
2
|
$dotenv = DotenvDotenv::createImmutable(__DIR__);
$dotenv->load();
|
- Access the environment variables in your PHP script using the $_ENV superglobal:
1
2
3
|
$db_host = $_ENV['DB_HOST'];
$db_user = $_ENV['DB_USER'];
$db_pass = $_ENV['DB_PASS'];
|
That's it! You have now loaded data from a .env file in PHP using the vlucas/phpdotenv library.