Using the .env file in the PHP project?

6

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

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

  • If yes, how?

    
asked by anonymous 11.10.2017 / 17:03

3 answers

3

As a matter of curiosity, I would like to inform you that the Library used to read this file .env is called vLucas / phpdotenv and can be installed via Composer . So you can deploy it to any project as long as you set it up correctly.

For example:

1 - Create a folder to test the library.

mkdir test_env

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

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

php composer.phar require vlucas/phpdotenv

3 - Create your .env file 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 think part of this question is already answered here:

11.10.2017 / 18:09
7

Files with arbitrary extension

Some systems / frameworks can choose text files with arbitrary extensions such as .env , .ini , .config and others, this does not make these files anything special, it is a mere convention, and should be treated on a case-by-case basis.

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

See the @GuilhermeNascimento response for an example of how to use parse_ini_file for the read portion of the file, and @Wallace's answer for details on the project I mentioned below.

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

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

  

link

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

With the above project, you just have to use the functions of% cos environment ), PHP has its own functions:


Using the environment with env

To access the environment data, simply use the special variable

$_ENV

(formerly it was $_ENV , which is obsolete. $HTTP_ENV_VARS is the "modern" way)

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

Example:

If in your environment you have this:

PATH=/root

when using

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

you will get $_POST

Using "/root"

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

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


Changing a value in the environment with getenv()

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


Documentation:

  

link

     

link

     

link

    
11.10.2017 / 17:08
4

I think if it is without the use of frameworks, it is also considering not using external libraries, so you parse the .ini with parse_ini_file (which can actually have any extension) that is very similar , 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 true :

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

It 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 $_ENV , Laravel uses it when the application does a requeste, adding the values of .env , but I personally think this is optional, even if you want to do it 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 executing this, but I do not see much because using it further.

Another option that I think might even be a bit simpler, would be to 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 usage would look like this:

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

Recommendation

I really recommend that you do not allow such files to be publicly accessible, Laravel itself is safe in itself, but a lot of people instead of pointing to VirtualHost for the public folder of it just move to public_html/public or www/public and create a .htaccess that rewrites the URL, so far so good, it may not be externally accessible, but if .htaccess is misconfigured content:

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

Files will be exposed, this can occur in your project too, so I recommend you be careful about this and if possible keep your .env out of the root folder of your server (usually public_html , www ) and if you can also only allow the file reading and handling for the operating system user who actually tweaks these files, then never use permissions like 777 .

    
11.10.2017 / 18:27