Php get env file

DOTENV in PHP

When we are creating a project, there are always some sensitive values, and at the beginning we don’t know where to write it and with that we end up writing it in my code, such as database passwords and others. But this is a big problem, firstly in terms of security because your data is visible to everyone with access to the code and secondly, it gets complicated whenever you change environments such as production and so on. And to solve this came .env , from which the point(dot) for linux environment is to leave files hidden, and the name env is an abbreviation for environment. To understand better, let’s see it in practice.

CODE

First let’s check the values that are in the environment variables and for that we can use getenv() ;

💡 NOTE: It is a good practice to have environment variable names in uppercase In addition to getenv we also have $_ENV $_ENV is an associative array where each of its keys is an environment variable pointing to its value. The problem is that it might not load depending on the php.ini configuration. To enable it, put the “E” option in the “variables_order” directive, where each letter represents a superglobal to be loaded. And to display the value we use

Now that we know where the variables are, how to create more and how to call just one, let’s make php read the values from an .env file and save it in the environment variables inside php.

Читайте также:  Проверка правильности email javascript

DOTENV

APP_NAME=Project APP_ENV=local 

PHP CLASS

 namespace App\Controller; class DotEnvEnvironment  public function load($path): void  $lines = file($path . '/.env'); foreach ($lines as $line)  [$key, $value] = explode('=', $line, 2); $key = trim($key); $value = trim($value); putenv(sprintf('%s=%s', $key, $value)); $_ENV[$key] = $value; $_SERVER[$key] = $value; > > > 
 require __DIR__ . '/../vendor/autoload.php'; (new App\Controller\DotEnvEnvironment)->load(__DIR__ . '/../'); echo getenv('APP_ENV'); echo $_ENV['APP_NAME']; 

.gitignore

Never send the .env to the server from the code, because the purpose of the .env is to separate sensitive information from the code so it doesn’t matter if you still send it to the server, and to avoid this just add the value to the .gitignore file.

If you are developing as a team, you can include the .env.example file and add some fictitious values there so that those who use the project can understand what should be done example.

DATABASE=database-name PASSWORD=your-password-here 

TIP

You can use different .env files per environment, so you can have .env.staging for staging, .env.production for production, .env.testing for testing, etc.

Library

Despite having shown how to create a file that loads .env , I don’t think it’s the best solution, as there are already libraries ready, more robust and much more tested, so if you’re just curious to understand how it works, go ahead and create your own, but if you want to create or use it in a professional project I recommend the vlucas/phpdotenv library, so excellent that the laravel framework itself uses and therefore I will show you how to use it. 💡 NOTE: symfony/dotenv is used in Symfony framework and sometimes i use it too First add it to composer

composer require vlucas/phpdotenv 
APP_NAME=Project APP_ENV=local 

Источник

getenv

Получает значение одной или всех переменных окружения.

Список всех переменных окружения можно посмотреть с помощью функции phpinfo() . Многие из этих переменных есть в документе » RFC 3875, по большей части в разделе 4.1, «Request Meta-Variables».

Список параметров

Имя переменной в виде строки ( string ) или null .

Если установлено значение true , возвращаются только локальные переменные окружения, установленные операционной системой или командой putenv. Это имеет значение только в том случае, если параметр name является строкой ( string ).

Возвращаемые значения

Возвращает значение переменной окружения name или false , если переменная окружения name не существует. Если name равно null , возвращаются все переменные окружения в виде ассоциативного массива ( array ).

Список изменений

Версия Описание
8.0.0 Параметр name теперь допускает значение null .
7.1.0 Параметр name теперь может быть опущен для получения ассоциативного массива ( array ) всех переменных окружения.
7.0.9 Был добавлен параметр local_only .

Примеры

Пример #1 Пример использования getenv()

// Пример использования getenv()
$ip = getenv ( ‘REMOTE_ADDR’ );

// Можно ещё воспользоваться суперглобальной переменной ($_SERVER или $_ENV)
$ip = $_SERVER [ ‘REMOTE_ADDR’ ];

// Гарантированно получаем значение переменной окружения, не обращая внимания,
// была ли она переопределена SAPI или изменена с помощью putenv
$ip = getenv ( ‘REMOTE_ADDR’ , true ) ?: getenv ( ‘REMOTE_ADDR’ );
?>

Примечания

Если PHP запущен в SAPI, например как Fast CGI, эта функция будет возвращать значения переменных окружения установленных SAPI, даже если вы использовали putenv() для установки локальной переменной с таким же именем. Используйте параметр local_only для получения установленных локально переменных.

Смотрите также

  • putenv() — Устанавливает значение переменной среды
  • apache_getenv() — Возвращает переменную окружения подпроцесса сервера Apache
  • Суперглобальные переменные

User Contributed Notes 14 notes

Contrary to what eng.mrkto.com said, getenv() isn’t always case-insensitive. On Linux it is not:

var_dump ( getenv ( ‘path’ )); // bool(false)
var_dump ( getenv ( ‘Path’ )); // bool(false)
var_dump ( getenv ( ‘PATH’ )); // string(13) «/usr/bin:/bin»

I did a benchmark about env.

constants :
0.00067687034606934 ms
getenv :
0.056761026382446 ms

And, in Windows at leat, reading the env value is considerably slow (in comparison with a constant), so PHP doesn’t cache the information and asks to the OS the env value per call.

So, if you are calling once per request, then there is not a problem. However, if you are calling it many times per request, then it could affects the performance.

This function is useful (compared to $_SERVER, $_ENV) because it searches $varname key in those array case-insensitive manner.
For example on Windows $_SERVER[‘Path’] is like you see Capitalized, not ‘PATH’ as you expected.
So just:

As noted on httpoxy.org, getenv() can confuse you in having you believe that all variables come from a «safe» environment (not all of them do).

In particular, $_SERVER[‘HTTP_PROXY’] (or its equivalent getenv(‘HTTP_PROXY’)) can be manually set in the HTTP request header, so it should not be considered safe in a CGI environment.

In short, try to avoid using getenv(‘HTTP_PROXY’) without properly filtering it.

All of the notes and examples so far have been strictly CGI.
It should not be understated the usefulness of getenv()/putenv() in CLI as well.

You can pass a number of variables to a CLI script via environment variables, either in Unix/Linux bash/sh with the «VAR=’foo’; export $VAR» paradigm, or in Windows with the «set VAR=’foo'» paradigm. (Csh users, you’re on your own!) getenv(«VAR») will retrieve that value from the environment.

We have a system by which we include a file full of putenv() statements storing configuration values that can apply to many different CLI PHP programs. But if we want to override these values, we can use the shell’s (or calling application, such as ant) environment variable setting method to do so.

This saves us from having to manage an unmanageable amount of one-off configuration changes per execution via command line arguments; instead we just set the appropriate env var first.

As you know, getenv(‘DOCUMENT_ROOT’) is useful.
However, under CLI environment(I tend to do quick check
if it works or not), it doesn’t work without modified php.ini
file. So I add «export DOCUMENT_ROOT=~» in my .bash_profile.

for quick check of getenv() adding a new env variable —
if you add a new env variable, make sure not only apache but xampp is also restarted.
Otherwise getenv() will return false for the newly added env variable.

It is worth noting that since getenv(‘MY_VARIABLE’) will return false when the variable given is not set, there is no direct way to distinguish between a variable that is unset and one that is explicitly set to the value bool(false) when using getenv().
This makes it somewhat tricky to have boolean environment variables default to true if unset, which you can work around either by using «falsy» values such as 0 with the strict comparison operators or by using the superglobal arrays and isset().

From PHP 7.1 => getenv() no longer requires its parameter. If the parameter is omitted, then the current environment variables will be returned as an associative array.

SERVER_NAME is the name defined in the apache configuration.
HTTP_HOST is the host header sent by the client when using the more recent versions of the http protocol.

When writing CLI applications, not that any environment variables that are set in your web server config will not be passed through. PHP will pass through system environment variables that are prefixed based off the safe_mode_allowed_env_vars directive in your php.ini

Beware that when using this function with PHP built-in server – i.e. php -S localhost:8000 – it will return boolean FALSE.

The example on how to fallback produces a syntax error on PHP 5.2:

$ip = getenv ( ‘REMOTE_ADDR’ , true ) ?: getenv ( ‘REMOTE_ADDR’ )

?>

-bash-3.2$ /web/cgi-bin/php5 test.php
Content-type: text/html

Parse error: syntax error, unexpected ‘:’ in /home/content/25/11223125/test.php on line 3

$ip = getenv(‘REMOTE_ADDR’, true) ? getenv(‘REMOTE_ADDR’, true) : getenv(‘REMOTE_ADDR’)

A function returning the remote adress of the visiting browser could look like this:

function getIPfromXForwarded () <
$ipString =@ getenv ( «HTTP_X_FORWARDED_FOR» );
$addr = explode ( «,» , $ipString );
return $addr [ sizeof ( $addr )- 1 ];
>
?>

Note that some adresses are followed by a whitespace and ip2long(getIPfromXForwarded()) would not return the expected result.

Make use of trim() in your scripts, either in the function itself, or the surrounding space of the caller.

  • Опции PHP/информационные функции
    • assert_​options
    • assert
    • cli_​get_​process_​title
    • cli_​set_​process_​title
    • dl
    • extension_​loaded
    • gc_​collect_​cycles
    • gc_​disable
    • gc_​enable
    • gc_​enabled
    • gc_​mem_​caches
    • gc_​status
    • get_​cfg_​var
    • get_​current_​user
    • get_​defined_​constants
    • get_​extension_​funcs
    • get_​include_​path
    • get_​included_​files
    • get_​loaded_​extensions
    • get_​required_​files
    • get_​resources
    • getenv
    • getlastmod
    • getmygid
    • getmyinode
    • getmypid
    • getmyuid
    • getopt
    • getrusage
    • ini_​alter
    • ini_​get_​all
    • ini_​get
    • ini_​parse_​quantity
    • ini_​restore
    • ini_​set
    • memory_​get_​peak_​usage
    • memory_​get_​usage
    • memory_​reset_​peak_​usage
    • php_​ini_​loaded_​file
    • php_​ini_​scanned_​files
    • php_​sapi_​name
    • php_​uname
    • phpcredits
    • phpinfo
    • phpversion
    • putenv
    • set_​include_​path
    • set_​time_​limit
    • sys_​get_​temp_​dir
    • version_​compare
    • zend_​thread_​id
    • zend_​version
    • get_​magic_​quotes_​gpc
    • get_​magic_​quotes_​runtime
    • restore_​include_​path

    Источник

Оцените статью