Load Environment Variables from (.env) File using PHP Tutorial

In this tutorial, you will learn how to Load the Environment Variables from a (.env) File using PHP Language. The tutorial aims to provide IT/CS students and new programmers with a reference to learn for loading environment variables in PHP. Here, a step-by-step tutorial and sample snippets are provided to understand the process for achieving the goal of this tutorial. A sample source code zip file is also provided and is free to download.

What are Environment Variables?

An environment variable is a value that is dynamically set and utilized throughout the program to control how a program behaves on each device. They are a component of the setting in which software runs. It is mostly used to store the variables that are needed in a web application and give you the ability to configure a value in your code without opening the file script where the variable is/are called. The Environment Variables give you the benefits to increase security and Simple to maintain and flexible code.

Example

Here's an example of an environment variable in a (.env) File.

  1. ##MY API Credentials
  2. web_api_client_id = 78895asda25as54dsaaa5wgb
  3. web_api_seckret_key = 668a7dasd8aw85xc8778a78wd$!@8

How to Load Environment Variables from (.env) file using PHP?

Here are the following steps to load the environment variables from the (.env) file using PHP:

Step 1

Identify the path of the (.env) file.

  1. <?php
  2. $env_file_path = realpath(__DIR__."/.env");
  3. ?>

Step 2

Check if the (.env) file exists. Also, check if the file permission is writable and readable.

  1. <?php
  2. //Check .envenvironment file exists
  3. if(!is_file($env_file_path)){
  4. throw new ErrorException("Environment File is Missing.");
  5. }
  6. //Check .envenvironment file is readable
  7. if(!is_readable($env_file_path)){
  8. throw new ErrorException("Permission Denied for reading the ".($env_file_path).".");
  9. }
  10. //Check .envenvironment file is writable
  11. if(!is_writable($env_file_path)){
  12. throw new ErrorException("Permission Denied for writing on the ".($env_file_path).".");
  13. }

Step 3

List all the variables from the (.env) file and its value. To do that, you must read the file in each line to capture the variables and skip the comment data and empty lines. You can do that using the PHP fopen() built-in function

  1. <?php
  2. $var_arrs = array();
  3. // Open the .en file using the reading mode
  4. $fopen = fopen($env_file_path, 'r');
  5. if($fopen){
  6. //Loop the lines of the file
  7. while (($line = fgets($fopen)) !== false){
  8. // Check if line is a comment
  9. $line_is_comment = (substr(trim($line),0 , 1) == '#') ? true: false;
  10. // If line is a comment or empty, then skip
  11. if($line_is_comment || empty(trim($line)))
  12. continue;
  13.  
  14. // Split the line variable and succeeding comment on line if exists
  15. $line_no_comment = explode("#", $line, 2)[0];
  16. // Split the variable name and value
  17. $env_ex = preg_split('/(\s?)\=(\s?)/', $line_no_comment);
  18. $env_name = trim($env_ex[0]);
  19. $env_value = isset($env_ex[1]) ? trim($env_ex[1]) : "";
  20. $var_arrs[$env_name] = $env_value;
  21. }
  22. // Close the file
  23. fclose($fopen);
  24. }

Step 4

Lastly, store and set the value of the environment variable in the PHP superglobal associative array. Using $_ENV or putenv().

  1. <?php
  2. foreach($var_arrs as $name => $value){
  3. //Using putenv()
  4. putenv("{$name}={$value}");
  5.  
  6. //Or, using $_ENV
  7. $_ENV[$name] = $value;
  8.  
  9. // Or you can use both
  10. }
  11. ?>

Retrieving Environment Variables Values

Here's the sample snippet on how to retrieve the value of the environment variable stored in PHP's superglobal array.

  1. <?php
  2. //For putenv(), use getenv()
  3. echo getenv('web_api_client_id');
  4.  
  5. //For $_ENV
  6. echo $_ENV['web_api_client_id'];
  7.  
  8. ?>

PHP Class to Load Environment Variables

The script below is a simple and working PHP Class that I created for loading the environment variables from (.env) files into an application. Feel free to use it for your own PHP Projects.

  1. <?php
  2.  
  3. class DotEnvironment {
  4. private $path;
  5. private $tmp_env;
  6. function __construct($env_path = ""){
  7. // Check if .env file path has provided
  8. if(empty($env_path)){
  9. throw new ErrorException(".env file path is missing");
  10. }
  11. $this->path = $env_path;
  12.  
  13. //Check .envenvironment file exists
  14. if(!is_file(realpath($this->path))){
  15. throw new ErrorException("Environment File is Missing.");
  16. }
  17. //Check .envenvironment file is readable
  18. if(!is_readable(realpath($this->path))){
  19. throw new ErrorException("Permission Denied for reading the ".(realpath($this->path)).".");
  20. }
  21. $this->tmp_env = [];
  22. $fopen = fopen(realpath($this->path), 'r');
  23. if($fopen){
  24. while (($line = fgets($fopen)) !== false){
  25. // Check if line is a comment
  26. $line_is_comment = (substr(trim($line),0 , 1) == '#') ? true: false;
  27. if($line_is_comment || empty(trim($line)))
  28. continue;
  29.  
  30. $line_no_comment = explode("#", $line, 2)[0];
  31. $env_ex = preg_split('/(\s?)\=(\s?)/', $line_no_comment);
  32. $env_name = trim($env_ex[0]);
  33. $env_value = isset($env_ex[1]) ? trim($env_ex[1]) : "";
  34. $this->tmp_env[$env_name] = $env_value;
  35. }
  36. fclose($fopen);
  37. }
  38. $this->load();
  39. }
  40.  
  41. function load(){
  42. // Save .env data to Environment Variables
  43. foreach($this->tmp_env as $name=>$value){
  44. putenv("{$name}=$value");
  45. if(is_numeric($value))
  46. $value = floatval($value);
  47. if(in_array(strtolower($value),["true","false"]))
  48. $value = (strtolower($value) == "true") ? true : false;
  49. $_ENV[$name] = $value;
  50. }
  51. // print_r(realpath($this->path));
  52. }
  53. }
  54. ?>

The usage of the DotEnvironment Class is like the following snippet.

  1. <?php
  2. // Load DotEnvironment Class
  3. require_once('./class.environment.php');
  4. $__DotEnvironment = new DotEnvironment(realpath(__DIR__."\.env"))
  5. echo "<pre>";
  6. print_r($_ENV)
  7. echo "</pre>";
  8. ?>

There you go! That's the end of this tutorial. I hope this Load Environment Variables from (.env) File using PHP Tutorial helps you with what you are looking for and that you'll find this useful for your current and future PHP Projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)

Add new comment