How to load data from .env file in php?

by darrion.kuhn , in category: PHP General , a year ago

How to load data from .env file in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , 2 months ago

@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:

  1. Install the vlucas/phpdotenv library using Composer by running the following command in your terminal:
1
composer require vlucas/phpdotenv


  1. 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


  1. Create a PHP script and require the autoload file from the vendor directory:
1
require 'vendor/autoload.php';


  1. Load the environment variables from the .env file using the Dotenv class:
1
2
$dotenv = DotenvDotenv::createImmutable(__DIR__);
$dotenv->load();


  1. 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.