What is an env file and how to use an env file in PHP?

MD UDOY HASAN
8 min readFeb 6, 2021

--

.env file in php
Collected from rootlearner.com

At present, an env file is an important part of both websites and apps. Now the internet is more complex than it was before. There are many hackers who want to hack your site for no reason. So, it is good to be always prepared. That’s why an env file makes its place in this situation.

So what is an env file?

Two fundamental components of any computer programming language are variables and constants. Like independent variables in a mathematical equation, these take on values that change the results of the program. Variables and constants both represent unique memory locations containing data the program uses in its calculations. The difference between the two is that variables values may change during execution, while constant values cannot be reassigned.

env files are also known as environment variables. An environment variable is a variable whose value is set outside the program, typically through a functionality built into the operating system or microservice. An environment variable is made up of a name/value pair, and any number may be created and available for reference at a point in time.

Why we should use an env file in the application?

To protect your application sensitive data access you need to use the env file. The sensitive data can be an API credential, MySQL Database login details, Application Rest APIs, etc. Suppose if you don’t use an env file and store all this sensitive data in simple PHP files or other files. Then if someone cracks your site we will also get access to all your these sensitive data along with site files. So, he can misuse this data and put you in trouble. So, that’s why we should use an env file in our application.

If we use the env file in our application nobody will get access to our env file. Because an important thing that you need to know is:

A web application file name that starts with a dot (.) like .env .htaccess is not accessible by any users

And to ensure more security you can set these dot( . ) files permission to 444. In this way, it will be harder for someone to see these file permissions. But your site will have permission to execute the code of this file. So, if you do all these things and your site gets crack by someone he will only your sever’s files and will not get the env file, In this way, your sensitive information will remain safe from bad people.

How to use the env file in a PHP application or project?

It is a good decision that you want to use the env file in your PHP application project. So, now the question is how the use or set up this env file in your PHP project. No worries now I’ll share how to use the env file with PHP. It is a very simple task to use the env file

To set up the env file you need composer preinstalled on your machine (PC, Laptop, etc.). So if you already have composer preinstalled then you are ready to set up the env file in your project. If you didn’t install the composer before then please install it before you can proceed. If you don’t know what is the composer and how to install it then visit What is the composer and how to install and use it?

Now when your machine has the composer just create a folder for your project. In this article we are opening a folder named dotenvdemo. Then create a index.php or any PHP file that you want to use the env file environment variables and also create a file named .env. In this article, we are using a index.php file. Before starting the project our file structure is:

dotenv-demo
├── index.php
└── .env

After creating your folder and PHP file just run this command in your terminal. But be sure to open the directory path in the terminal you can use cd to open the directory path.

cd your_directory_path

On my pc it is

cd E:\xampp\htdocs\dotenv-demo

E:\xampp\htdocs\dotenv-demo is the directory path in my pc

So after opening the path in your terminal just run the following command.

composer require vlucas/phpdotenv

Then you will see that it will install all required packages/files for the env file setup. Now when the package install process is done our project structure will be like this:

dotenv-demo
├── vendor
│ ├── composer
│ │ ├── autoload_classmap.php
│ │ ├── autoload_files.php
│ │ ├── autoload_namespaces.php
│ │ ├── autoload_psr4.php
│ │ ├── autoload_real.php
│ │ ├── autoload_static.php
│ │ ├── ClassLoader.php
│ │ ├── installed.json
│ │ ├── installed.php
│ │ ├── InstalledVersions.php
│ │ ├── LICENSE
│ │ └── platform_check.php
│ ├── graham-campbell
│ │ └── result-type
│ │ ├── src
│ │ │ ├── Error.php
│ │ │ ├── Result.php
│ │ │ └── Success.php
│ │ ├── composer.json
│ │ └── LICENSE
│ ├── phpoption
│ │ └── phpoption
│ │ ├── src
│ │ │ └── PhpOption
│ │ │ ├── LazyOption.php
│ │ │ ├── None.php
│ │ │ ├── Option.php
│ │ │ └── Some.php
│ │ ├── composer.json
│ │ ├── LICENSE
│ │ └── Makefile
│ ├── symfony
│ │ ├── polyfill-ctype
│ │ │ ├── bootstrap.php
│ │ │ ├── composer.json
│ │ │ ├── Ctype.php
│ │ │ ├── LICENSE
│ │ │ └── README.md
│ │ ├── polyfill-mbstring
│ │ │ ├── Resources
│ │ │ │ └── unidata
│ │ │ │ ├── lowerCase.php
│ │ │ │ ├── titleCaseRegexp.php
│ │ │ │ └── upperCase.php
│ │ │ ├── bootstrap.php
│ │ │ ├── composer.json
│ │ │ ├── LICENSE
│ │ │ ├── Mbstring.php
│ │ │ └── README.md
│ │ └── polyfill-php80
│ │ ├── Resources
│ │ │ └── stubs
│ │ │ ├── Attribute.php
│ │ │ ├── Stringable.php
│ │ │ ├── UnhandledMatchError.php
│ │ │ └── ValueError.php
│ │ ├── bootstrap.php
│ │ ├── composer.json
│ │ ├── LICENSE
│ │ ├── Php80.php
│ │ └── README.md
│ ├── vlucas
│ │ └── phpdotenv
│ │ ├── src
│ │ │ ├── Exception
│ │ │ │ ├── ExceptionInterface.php
│ │ │ │ ├── InvalidEncodingException.php
│ │ │ │ ├── InvalidFileException.php
│ │ │ │ ├── InvalidPathException.php
│ │ │ │ └── ValidationException.php
│ │ │ ├── Loader
│ │ │ │ ├── Loader.php
│ │ │ │ ├── LoaderInterface.php
│ │ │ │ └── Resolver.php
│ │ │ ├── Parser
│ │ │ │ ├── Entry.php
│ │ │ │ ├── EntryParser.php
│ │ │ │ ├── Lexer.php
│ │ │ │ ├── Lines.php
│ │ │ │ ├── Parser.php
│ │ │ │ ├── ParserInterface.php
│ │ │ │ └── Value.php
│ │ │ ├── Repository
│ │ │ │ ├── Adapter
│ │ │ │ │ ├── AdapterInterface.php
│ │ │ │ │ ├── ApacheAdapter.php
│ │ │ │ │ ├── ArrayAdapter.php
│ │ │ │ │ ├── EnvConstAdapter.php
│ │ │ │ │ ├── GuardedWriter.php
│ │ │ │ │ ├── ImmutableWriter.php
│ │ │ │ │ ├── MultiReader.php
│ │ │ │ │ ├── MultiWriter.php
│ │ │ │ │ ├── PutenvAdapter.php
│ │ │ │ │ ├── ReaderInterface.php
│ │ │ │ │ ├── ReplacingWriter.php
│ │ │ │ │ ├── ServerConstAdapter.php
│ │ │ │ │ └── WriterInterface.php
│ │ │ │ ├── AdapterRepository.php
│ │ │ │ ├── RepositoryBuilder.php
│ │ │ │ └── RepositoryInterface.php
│ │ │ ├── Store
│ │ │ │ ├── File
│ │ │ │ │ ├── Paths.php
│ │ │ │ │ └── Reader.php
│ │ │ │ ├── FileStore.php
│ │ │ │ ├── StoreBuilder.php
│ │ │ │ ├── StoreInterface.php
│ │ │ │ └── StringStore.php
│ │ │ ├── Util
│ │ │ │ ├── Regex.php
│ │ │ │ └── Str.php
│ │ │ ├── Dotenv.php
│ │ │ └── Validator.php
│ │ ├── composer.json
│ │ ├── LICENSE
│ │ ├── Makefile
│ │ └── phpstan.src.neon.dist
│ └── autoload.php
├── .env
├── composer.json
├── composer.lock
└── index.php

So, 75% of our work is done. Now you can set up the env file and other PHP. Before running the composer command I’ve told you that we will be using the index.php file as the main file that we want to get the env file environment variables. You can use any other name also for example envloader.php. So as I’ve used the index.php file, the file structure will be like this:

<?phprequire_once realpath(__DIR__ . "/vendor/autoload.php");
use Dotenv\Dotenv;
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

You need to put this code in every PHP file that uses the environment variables. If you have multiple PHP files that need the environment variables you can simply create a common file using this code. Suppose you create a file named loadenv.php and include the file in other PHP files. using include or require or require_once.

Now, we are all set to go just open the env file and add your data like this

APP_NAME=ExampleAPP
APP_VERSION=vX.X.X
APP_REST_API=XXXXX-XXXXXX-XXXXXX-XXXXX-XXXXX
Weather_Api=XXXXX-XXXXX-XXXXXX-XXXXX-XXXXX
Weater_Api_Secret=XXXXX-XXXXX-XXXXX-XXXXX
MySQL_DB_HOST=localhost
MySQL_DB_USER_NAME=exampleuser
MySQL_DB_PASSWORD=XXXXXXXXXXX
MySQL_DB_NAME=example

Now we can get these variable values from the PHP files. Always an env file contains 2 pars the environment variable name and its value. In the example, we have used APP_NAME as an environment variable name and ExampleAPP is the value of that environment variable.

So, now what question comes to our mind. How to get the data from the env file and show the data in our PHP files. So, to do that we need to make sure that the specific PHP file has the code that we have used in the index.php . Now, when our file has the code we can use $_ENV['variable _name'] to get the environment variable value. Like if we want to get the app name:

<?php//load .env file
require_once realpath(__DIR__ . "/vendor/autoload.php");
use Dotenv\Dotenv;
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();
//get app name from .env file
$appName = $_ENV['APP_NAME'];
//echo the app name
echo $appName;

Remember you can also use getenv() instead of $_ENV[]. But we discourage you to use getenv() instead of $_ENV[] because of security reasons.

Conclusion

So, by reading this article now you may have understood the importance of the env file and also the way to use the env file in PHP projects. I but remember if you are building a project for GitHub make sure not to upload the real env file to Github. Always upload a .env.sample file to Github. And if you are pushing the codes directly to your GitHub repo then create a .gitignore file and ignore the env file there. It will save your env file from automatically pushing the file to Github.

All the code that I’ve used in this article, I’ve uploaded all files to my GitHub repo. You can download all the codes from there. If you face problems with any of this code. Please comment in the comment box I will love to fix that for you then. Good Bye, for now, see you in the next article.

--

--

MD UDOY HASAN
MD UDOY HASAN

Written by MD UDOY HASAN

Hi I'm a professional web and applcation developer. I can build anything if you can dream about it