Use . env file in PHP project?

Asked

Viewed 11,575 times

14

I realized that in the Laravel uses the file .env for some settings and in the code it a function env(), ask:

  • Is there any way to use the file .env in my project php without using any framework?

  • If yes, how?

Observing: I’ve done several researches and not yet discovered.

  • getenv() would be the correct function name.

4 answers

10

Files with arbitrary extension

Some systems/frameworks may elect text files with arbitrary extensions such as .env, .ini, .config and others, this does not make these archives anything special, it is mere convention, and must be treated case by case.

In Laravel’s case, the file .env is mere configuration, a normal text file, with nothing in particular, which is usually in the directory config, and is used in addition (being loaded into the environment by a function of its own).

See @Guilhermenascimento’s reply for an example of how to use parse_ini_file for the read part of the file, and in @Wallace’s reply more details on the project I mentioned just below.

The idea here is that by putting some information in the environment, you are protecting your application (example: access credentials that are not in a text file, protected from accidental copies), and having others less sensitive in conventional files to facilitate copying and migration.

To use in your projects (tip @bfavaretto gave in the comments) has this project on Github that loads the file variables .env in the system environment:

https://github.com/vlucas/phpdotenv

With this feature, you can merge file usage .env with environment variables, having the mentioned advantage of leaving in file what is less sensitive, and configuring directly in the system things that should not be copied.

With the above project, simply use the functions of env (Environment = environment) of the operating system, PHP has its own functions:


Using the environment with $_ENV

To access environment data just use the special variable

$_ENV

(formerly era $HTTP_ENV_VARS, outdated. $_ENV is the way "modern")

It works in a manner analogous to $_GET, $_POST etc..

Example:

If in your environment you have it:

PATH=/root

when using

$caminho = $_ENV['PATH'];
echo $caminho;

will get "/root"


Using getenv()

The function getenv() values for it. See the code equivalent to the previous one, using the function instead of the pre-populated variable:

$caminho = getenv('PATH');
echo $caminho;


Changing an environment value with putenv()

The function putenv() allows you to change/define a value in the environment, always remembering that it is valid for the current session. If you want permanent changes, you need to use OS resources (or in the case of Laravel, edit the file . env)


Documentation:

http://php.net/manual/en/reserved.variables.environment.php

http://php.net/manual/en/function.getenv.php

http://php.net/manual/en/function.putenv.php

  • he says it’s obsolete

  • It is not. Read the linked manual . However, I updated it to clarify.

  • From what I’ve seen, Laravel uses . env with this https://github.com/vlucas/phpdotenv

  • There is a way for me to use a file . env as well?

  • I incorporated the @bfavaretto link in the answer, I believe it solves for you to use . env in your projects with the above functions, without having to write your own code for this.

9


As a curiosity, I inform you that the Library used to read this file .env is called vLucas/phpdotenv and can be installed via Composer. Therefore, you can implement it in any project, as long as you configure it correctly.

For example:

1 - Create a folder to test the library.

mkdir test_env

2 - Then select this folder and install the vlucas/phpdotenv through the Composer:

curl -s http://getcomposer.org/installer | php

php composer.phar require vlucas/phpdotenv

3 - Create your file .env in the same folder.

#.env
PROJECT_NAME="Test Env"

4 - Create a file index.php

// Esse arquivo e pasta é gerado depois de instalação da biblioteca descrita acima
include_once __DIR__ . '/vendor/autoload.php';

$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();

var_dump(getenv('PROJECT_NAME'));
var_dump($_ENV['PROJECT_NAME']);

I believe that part of that question is already answered here:

  • Gave Fatal error: Call to undefined function env() in D:\wamp\www\testeenv\index.php on line 9
Call Stack

  • 1

    @adventistaam I think I missed that point, try getenv kindly.

  • @adventistaam was exactly that. The correct is getenv

  • now it has worked

  • 1

    as I am using in windows the line with the command curl -s http ... did not work, but I used the command php -r "readfile('https://getcomposer.org/installer');" | php and I was able to continue

  • 1

    Another option I found to be much more robust is symfony dotenv.

Show 1 more comment

7

I believe that if it is without the use of frameworks, you are also considering not using external libraries. So, you parse the .ini with parse_ini_file (which may actually have any extension) which is similar good, for example:

$parsed = parse_ini_file('config/foo.env');

If the contents of the file are:

; Comentários começam com ';'

[database]
mysql_host = foo.com
mysql_login = baz
mysql_pass = foobarbaz

[debug]
enable = false
error_level = 32767 ; = E_ALL

[requirements]
phpversion[] = "5.6"
phpversion[] = "7.0"
phpversion[] = "7.1"
phpversion[] = "7.2"

It will generate this (without the "sessions"):

Array
(
    [mysql_host] => foo.com
    [mysql_login] => baz
    [mysql_pass] => foobarbaz
    [enable] => 0
    [error_level] => 32767
    [phpversion] => Array
        (
            [0] => 5.6
            [1] => 7.0
            [2] => 7.1
            [3] => 7.2
        )

)

If you want to use the sessions add the true:

$parsed = parse_ini_file('config/foo.env', true);

Will generate this:

Array
(
    [database] => Array
        (
            [mysql_host] => foo.com
            [mysql_login] => baz
            [mysql_pass] => foobarbaz
        )

    [debug] => Array
        (
            [enable] => 0
            [error_level] => 32767
        )

    [requirements] => Array
        (
            [phpversion] => Array
                (
                    [0] => 5.0
                    [1] => 5.1
                    [2] => 5.2
                    [3] => 5.3
                )
        )
)

Of course it is not mandatory to use the $_ENV, Laravel uses when the application makes a request, adding the values of the .env, but I personally think that this is optional, yet if you wish to make can use this way:

$envs = parse_ini_file('config/foo.env');

foreach ($envs as $key => $value) {
    $_ENV[$key] = $value;
}

Of course it will only be available within the main script and after running it, but I don’t see much why use beyond this.

Another option that I think might even be a little simpler, would just use a function:

function MeuEnv($chave)
{
     static $envs;

     if (!$envs) {
          $envs = parse_ini_file('config/foo.env');
     }

     return empty($envs[$chave]) ? null : $envs[$chave];
}

And the use would look like this:

var_dump(MeuEnv('mysql_host'), MeuEnv('mysql_login'));

Recommending

I really recommend that you don’t allow files like this to be publicly accessible, Laravel himself is safe in itself, but a lot of people instead of pointing to Virtualhost to the folder public of it just move to public_html/public or www/public and create a .htaccess rewriting the URL, so far so good, maybe not accessible externally, but if . htaccess is poorly configured content this:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

The files will be exposed, this can occur in your project as well, so I recommend you to be careful with this and if possible keep yours .env outside your server’s root folder (usually public_html, www) and if you can also only allow file reading and handling to the operating system user who actually tweak these files, then never use permissions like 777.

  • 3

    The object is to leave the database settings outside the commits, and this is a great solution

  • @adventistaam only recommend putting sensitive data files, such as database authentication in a folder that is not publicly accessible via HTTP ;)

  • I get it. This is very important

  • 2

    In that reply I explained a lot about settings. It’s worth taking a look.

  • 3

    Why would I use a lib to read a file .env if it’s so simple to do it this way?

  • 1

    I agree with you @Rbz, my biggest criticism about PHP and Javascript communities (with NPM) is just this, and your question (which is probably rhetorical) answers very well, there is no advantage when it really is something simple like this, the only motivation that would be to use phpdotenv would be to use the auxiliary methods and also maintain compatibility with . env from other projects, where comments use "#" will end up being passed as https://ideone.com/YjyOInvalues ...

  • 1

    ... however I see no problem in it, since if there is a value with # as key you would only access if necessary, then it turns out that parse_ini also meets

  • 1

    This should be the best answer.

Show 3 more comments

-3

The way I use it is by adding a Conf.php file to the src folder of the project and configuring the file tag in Composer.json.

{
  "name": "vendor/projeto",
  "description": "A tool to help in a day hard work",
  "minimum-stability": "stable",
  "license": "proprietary",
  "authors": [
    {
      "name": "Seu Nome",
      "email": "[email protected]"
    }
  ],
  "autoload": {
    "files": [
      "src/Config.php"
    ]
  },
  "require": {
    "pacotes/externos": "aqui"
  }
}

Thus this file is automatically loaded for the entire project, there Voce can set the global settings of the application. Ex:

date_default_timezone_set("America/Sao_Paulo");
define("BASE_URL", "https://localhost/seu-site");
define("DATE_FORMAT_BR", "d-m-Y");
$month = [
    'janeiro'=>'01',
    'fevereiro'=>'02',
    'março'=>'03',
    'abril'=>'04',
    'maio'=>'05',
    'junho'=>'06',
    'julho'=>'07',
    'agosto'=>'08',
    'setembro'=>'09',
    'outubro'=>'10',
    'novembro'=>'11',
    'dezembro'=>'12',
];
  • 2

    Hello Ricaom. We are not a forum for suggestions. We are a site of questions and answers, you should read the statement of the question and answer exactly what the author asked and not give suggestions of what you find interesting. The question is about reading files .env, the answer should be on this. Thank you for understanding.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.