• We just launched and are currently in beta. Join us as we build and grow the community.

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

mh159

Anime Convention Pro
M Rep
0
0
0
Rep
0
M Vouches
0
0
0
Vouches
0
Posts
102
Likes
103
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 300 XP
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. // Split the line variable and succeeding comment on line if exists
  14. $line_no_comment

    =

    explode

    (

    "#"

    ,

    $line

    ,

    2

    )

    [

    0

    ]

    ;
  15. // Split the variable name and value
  16. $env_ex

    =

    preg_split

    (

    '/(\s?)\=(\s?)/'

    ,

    $line_no_comment

    )

    ;
  17. $env_name

    =

    trim

    (

    $env_ex

    [

    0

    ]

    )

    ;
  18. $env_value

    =

    isset

    (

    $env_ex

    [

    1

    ]

    )

    ? trim

    (

    $env_ex

    [

    1

    ]

    )

    :

    ""

    ;
  19. $var_arrs

    [

    $env_name

    ]

    =

    $env_value

    ;
  20. }
  21. // Close the file
  22. fclose

    (

    $fopen

    )

    ;
  23. }

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. //Or, using $_ENV
  6. $_ENV

    [

    $name

    ]

    =

    $value

    ;

  7. // Or you can use both
  8. }
  9. ?>

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. //For $_ENV
  5. echo

    $_ENV

    [

    'web_api_client_id'

    ]

    ;

  6. ?>

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

    DotEnvironment {
  3. private

    $path

    ;
  4. private

    $tmp_env

    ;
  5. function

    __construct(

    $env_path

    =

    ""

    )

    {
  6. // Check if .env file path has provided
  7. if

    (

    empty

    (

    $env_path

    )

    )

    {
  8. throw

    new

    ErrorException(

    ".env file path is missing"

    )

    ;
  9. }
  10. $this

    ->

    path

    =

    $env_path

    ;

  11. //Check .envenvironment file exists
  12. if

    (

    !

    is_file

    (

    realpath

    (

    $this

    ->

    path

    )

    )

    )

    {
  13. throw

    new

    ErrorException(

    "Environment File is Missing."

    )

    ;
  14. }
  15. //Check .envenvironment file is readable
  16. if

    (

    !

    is_readable

    (

    realpath

    (

    $this

    ->

    path

    )

    )

    )

    {
  17. throw

    new

    ErrorException(

    "Permission Denied for reading the "

    .

    (

    realpath

    (

    $this

    ->

    path

    )

    )

    .

    "."

    )

    ;
  18. }
  19. $this

    ->

    tmp_env

    =

    [

    ]

    ;
  20. $fopen

    =

    fopen

    (

    realpath

    (

    $this

    ->

    path

    )

    ,

    'r'

    )

    ;
  21. if

    (

    $fopen

    )

    {
  22. while

    (

    (

    $line

    =

    fgets

    (

    $fopen

    )

    )

    !==

    false

    )

    {
  23. // Check if line is a comment
  24. $line_is_comment

    =

    (

    substr

    (

    trim

    (

    $line

    )

    ,

    0

    ,

    1

    )

    ==

    '#'

    )

    ? true

    :

    false

    ;
  25. if

    (

    $line_is_comment

    ||

    empty

    (

    trim

    (

    $line

    )

    )

    )
  26. continue

    ;

  27. $line_no_comment

    =

    explode

    (

    "#"

    ,

    $line

    ,

    2

    )

    [

    0

    ]

    ;
  28. $env_ex

    =

    preg_split

    (

    '/(\s?)\=(\s?)/'

    ,

    $line_no_comment

    )

    ;
  29. $env_name

    =

    trim

    (

    $env_ex

    [

    0

    ]

    )

    ;
  30. $env_value

    =

    isset

    (

    $env_ex

    [

    1

    ]

    )

    ? trim

    (

    $env_ex

    [

    1

    ]

    )

    :

    ""

    ;
  31. $this

    ->

    tmp_env

    [

    $env_name

    ]

    =

    $env_value

    ;
  32. }
  33. fclose

    (

    $fopen

    )

    ;
  34. }
  35. $this

    ->

    load

    (

    )

    ;
  36. }

  37. function

    load(

    )

    {
  38. // Save .env data to Environment Variables
  39. foreach

    (

    $this

    ->

    tmp_env

    as

    $name

    =>

    $value

    )

    {
  40. putenv

    (

    "{$name}

    =$value

    "

    )

    ;
  41. if

    (

    is_numeric

    (

    $value

    )

    )
  42. $value

    =

    floatval

    (

    $value

    )

    ;
  43. if

    (

    in_array

    (

    strtolower

    (

    $value

    )

    ,

    [

    "true"

    ,

    "false"

    ]

    )

    )
  44. $value

    =

    (

    strtolower

    (

    $value

    )

    ==

    "true"

    )

    ? true

    :

    false

    ;
  45. $_ENV

    [

    $name

    ]

    =

    $value

    ;
  46. }
  47. // print_r(realpath($this->path));
  48. }
  49. }
  50. ?>

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 =)


Download
You must upgrade your account or reply in the thread to view hidden text.
 

442,401

317,942

317,951

Top