1

I have a .env file including following data:

DB_PORT=49500
APP_NAME=Python
APP_HTTP_PORT=49502
APP_HTTPS_PORT=49503

I want to use these variables in my index.html page like:

 <!DOCTYPE html>
   <html>
    <head>
        <meta charset="utf-8" />
        <title>**$APP_NAME** - Summary Page</title>
        <link rel="stylesheet" href="style.css" />
    </head>

How to use the variables from other file which is a .env file into my index.html page?

  • 1
    Using what server side language/setup? This may be a duplicate of https://stackoverflow.com/q/43040967/6083675 – Laurel Nov 05 '20 at 18:44
  • 2
    Not possible: HTML can't do that - it's a markup language, so you'll need some preprocessing to insert insert these variables, like Jinja. – ForceBru Nov 05 '20 at 18:44
  • @Laurel I am using html page to display normally the contents of the page. I just want the variables I use in that page to be replaced by the values which will come from .env file – Kanika Kohli Nov 05 '20 at 18:56
  • @KanikaKohli — And you need to use a programming language to do that replacement. So step 1 is picking a programming language. – Quentin Nov 06 '20 at 18:19

1 Answers1

-1

You need to use PHP to read the .env file and return those values to JavaScript (if wanted).

$filename = "your_env_file.env";
$file = fopen($filename, "r") or die("500 Server Error: Can't open file.");
$content = fread($file, filesize($filename));
fclose($file);
$lines = explode("\n", $content);
$info = array();
foreach($lines as $line)
{
    $data = explode("=", $line);
    $info[$data[0]] = rtrim($data[1], "\r");
}
$json_encoded_info = json_encode($info); // to send to JavaScript
/*
 * Now we can echo the $info array to the HTML with
 * echo $info;
 *
 * or we can send JS the variables using
*/

echo "<script>
var info = JSON.parse(\"".$json_encoded_info."\");
//Do something with the info here
</script>";

/*
 * Unfortunately, this shows all of your .env information in the string.
 * A better way is with AJAX.
 * See link reference below for more ways to do this.
 */

How do I pass variables and data from PHP to JavaScript?

What this code does is:

  1. Read all of the content of your .env file
  2. Split all of the lines
  3. Put all of the line information into $info

The comments explain what you can do with that information (echo to HTML, send to Javascript).

Looking at your question, it seems like you want to replace **APP_NAME** with its respective value. You can use Javascript to obtain the value from PHP (it should be Python in this case) through one of the methods in the linked Stack Overflow answer, and then replace **APP_NAME** (or whatever other key you want) with the value received from PHP.

Lakshya Raj
  • 1,669
  • 3
  • 10
  • 34