环境变量 变量名 变量值_如何使用环境变量

环境变量 变量名 变量值

Environment variables are a set of dynamic named values that can affect the way running processes will behave on a computer.

环境变量是一组动态的命名值,可以影响正在运行的进程在计算机上的行为方式。

In simple terms, Evironment Variables are variables that are set depending on the computer (server) the software is running on. Have you by chance heard "Add a program to PATH"? It could be PHP or composer — but you've heard something like this, especially when trying to install a software you use. PATH is an example of an Environment Variable.

简而言之,环境变量是根据运行软件的计算机(服务器)设置的变量。 您是否偶然听到“将程序添加到PATH ”? 它可能是PHP或作曲家-但您已经听到类似的声音,尤其是在尝试安装所用软件时。 PATH是环境变量的一个示例。

Testing is an integral part of app development. Some people test their code on a local machine. While others prefer to set up a live test server with the same configuration as their production server. Then they run their tests to see if the app will work fine in a production environment.

测试是应用程序开发不可或缺的一部分。 有些人在本地计算机上测试他们的代码。 而其他人则喜欢使用与生产服务器相同的配置来设置实时测试服务器。 然后,他们运行测试以查看该应用程序是否可以在生产环境中正常运行。

When I was first learning to version control my code with git, I was told to never put sensitive data in source code. Sensitive data includes database password, API keys etc. Now that we know not to put sensitive data in source, how then do we tell the application the pass key to use? The answer, you guessed it — Environment Variables.

当我第一次学习使用git对代码进行版本控制时,我被告知永远不要将敏感数据放在源代码中。 敏感数据包括数据库密码,API密钥等。既然我们知道不要在源中放入敏感数据,那么我们如何告诉应用程序要使用的密钥? 您猜对了答案-环境变量。

设置环境变量 ( Setting Environment Variables )

Setting environment variables differs on the operating system in question. I will show you how to environment variables in Linux and Windows environment, and finally using PHP.

设置环境变量在所讨论的操作系统上有所不同。 我将向您展示如何在Linux和Windows环境中环境变量,最后使用PHP。

在Linux中 ( In Linux )

To create an environment variable in Linux, we can just run the following command.

要在Linux中创建环境变量,我们只需运行以下命令。

export DB_PASSWORD="25v3(:/9C"s:WHA`"

to view the content of the environment variable, you can do this.

要查看环境变量的内容,可以执行此操作。

echo $DB_PASSWORD

And there, we have our super secure database password set. The problem with this method is that we lose the variable as soon as we close the terminal.

在那里,我们设置了超级安全的数据库密码。 这种方法的问题在于,一旦关闭终端,我们就会丢失变量。

To make it permanent, edit your .bashrc file and add the above command at the bottom of the file.

要使其永久,请编辑.bashrc文件,并将上述命令添加到文件底部。

I prefer writing all environment variables in a separate file and include the file in .bashrc file. To do that, go to root and create a new file, I call mine .bash_exports.

我更喜欢将所有环境变量写在一个单独的文件中,并将该文件包含在.bashrc文件中。 为此,请转到根目录并创建一个新文件,我将其.bash_exports

cd ~
touch .bash_exports

Then I use vim editor to include my exports and save the file. To include the file in .bashrc, open the .bashrc file and add this line at the bottom.

然后,我使用vim编辑器包括我的导出并保存文件。 要将文件包含在.bashrc ,请打开.bashrc文件,并在底部添加此行。

if [ -f $HOME/.bash_exports ]; then
    . $HOME/.bash_exports
fi

This checks to see if the file exists; if it does, source/import it.

这将检查文件是否存在。 如果是这样,请提供/导入它。

Windows中的环境变量 ( Enviroment Variables in Windows )

Setting environment variables in windows take a more graphical approach. Go to Control Panel\System and Security\System and in the left panel, click on Advanced system settings. A popup dialog appears, click on environment variables.

在Windows中设置环境变量采用了更加图形化的方法。 转到Control Panel\System and Security\System然后在左侧面板中,点击Advanced system settings 。 出现一个弹出对话框,单击环境变量。

环境变量 变量名 变量值_如何使用环境变量_第1张图片

In the popup that appears, there are two sections. The first one holds user variables while the second one holds system variables.

在出现的弹出窗口中,有两个部分。 第一个保存用户变量,第二个保存系统变量。

环境变量 变量名 变量值_如何使用环境变量_第2张图片

Not to confuse you, System Variables and User Variables both make up environment variables on Windows. The difference between them is that System Variables are system-wide, while User Variables are for the current user.

不要混淆您,系统变量和用户变量都构成Windows上的环境变量。 它们之间的区别在于,系统变量是系统范围的,而用户变量是针对当前用户的。

Now click on the new button on the section you decide to save the variable, a dialog pops up asking you to enter a key and a value and hit save. To see if the variable exists, open a command prompt and type

现在,在您决定保存变量的部分上单击new按钮,弹出一个对话框,要求您输入键和值,然后单击保存。 要查看变量是否存在,请打开命令提示符并键入

echo %NEW_VARIABLE_NAME%

and you should see the value of the variable. On Windows, the % sign before and after the variable name is important.

并且您应该看到变量的值。 在Windows上,变量名称前后的%符号很重要。

在PHP中设置环境变量 ( Setting Environment Variables In PHP )

To set an environment variable in PHP, we can use one of two ways. The first is using the $_ENV super global

要在PHP中设置环境变量,我们可以使用以下两种方法之一。 第一种是使用$_ENV超级全局

$_ENV['VARIABLE_NAME'] = 'super sentitive key';

or a more preferable way to set environment variables in PHP would be to use the putenv function.

或者在PHP中设置环境变量的更可取的方法是使用putenv函数。

putenv('KEY=VALUE');

使用PHP获取环境变量 ( Getting Environment Variables with PHP )

Just like setting environment variables, we can get environment variables using one of two methods. The first is to access the variable from the $_ENV superglobal, while the other requires us to use the more preferable getenv function.

就像设置环境变量一样,我们可以使用两种方法之一来获取环境变量。 第一个是从$_ENV超全局变量访问变量,而另一个则要求我们使用更可取的getenv函数。

echo $_ENV['PATH'];

or

要么

echo getenv('PATH');

处理PHP环境变量的更好方法 ( A Better Way to Handle Environment Variables in PHP )

The above method works fine. Most people just add this snippet to their application bootstrap file. This defeats the purpose of "never add sensitive data to version control".

上面的方法工作正常。 大多数人只是将此代码段添加到他们的应用程序引导文件中。 这违反了“从不向版本控制添加敏感数据”的目的。

We could come up with a way to use environment variables. We could create a PHP file and exclude that file from version control and then add all our Environment variables in that file. Then we could run a check that ensures the file exist, if not throw an error exception and alert the developer, telling them to create the file. This was what I used for a while until I found DotEnv. It was a much cleaner solution than using the file method above.

我们可以想出一种使用环境变量的方法。 我们可以创建一个PHP文件,并从版本控制中排除该文件,然后在该文件中添加所有环境变量。 然后,我们可以运行检查以确保文件存在(如果没有抛出错误异常),并警告开发人员,告诉他们创建文件。 这是我使用了一段时间,直到找到DotEnv 。 与使用上面的文件方法相比,这是一种更干净的解决方案。

DotEnv提供什么 ( What does DotEnv offer )

This library offers us the following set of features:

该库为我们提供了以下功能:

  • We can load variables to the environment.

    我们可以将变量加载到环境中。
  • Let's us define the environment variables that are must-use.

    让我们定义必须使用的环境变量。
  • Provides an env function as a shorthand to $option = getenv('VARIABLE') ? getenv('VARIABLE') : $default;.

    提供env函数作为$option = getenv('VARIABLE') ? getenv('VARIABLE') : $default;的简写$option = getenv('VARIABLE') ? getenv('VARIABLE') : $default; $option = getenv('VARIABLE') ? getenv('VARIABLE') : $default;
  • Nest environment variables.

    嵌套环境变量。
  • Validation for variables.

    验证变量。

DotEnv入门 ( Get Started with DotEnv )

This library needs you to create a .env file which you can put your environment variables as key-value pairs.

该库需要您创建一个.env文件,您可以将您的环境变量作为键值对。

Example .env file looks like this

示例.env文件如下所示

DB_NAME=database name
DB_PASSWORD=@$fq42$d2r2
DB_HOST="localhost"

The key is the string before the equals sign, while after the equals sign is the value. Notice the value can also be in quotes, it all depends on personal preference.

键是等号前面的字符串,等号后面是值。 注意,该值也可以用引号引起来,这完全取决于个人喜好。

First before we can use the library, we can download the package from github or install it via composer. Let's install our copy with composer.

首先,在使用该库之前,我们可以从github下载该软件包或通过composer安装它。 让我们使用composer安装副本。

composer require --dev phpdotenv

After installing the library, we can then create our index.php file and include composer autoloader.

安装库之后,我们可以创建我们的index.php文件并包含composer自动加载器。

require __DIR__ . '/vendor/autoload.php';

after autoloading the installed package, we can then tell DotEnv to load the .env file.

自动加载已安装的软件包后,我们可以告诉DotEnv加载.env文件。

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

DotEnv constructor takes the directory of the .env file. Optionally, we can change the name of the environment loader file.

DotEnv构造函数采用.env文件的目录。 (可选)我们可以更改环境加载器文件的名称。

$dotenv = new Dotenv\Dotenv(__DIR__, 'new-config-file-name');
$dotenv->load();

访问DotEnv数据 ( Accessing DotEnv Data )

Like we earlier mentioned, we could use the getenv php function to get the value from the environment. But DotEnv provides an env function that we can use. env is shorter than getenv and most importantly, takes in a second parameter that acts as the default value.

就像我们前面提到的,我们可以使用getenv php函数从环境中获取值。 但是DotEnv提供了我们可以使用的env函数。 envgetenv短,最重要的是,它接受第二个参数作为默认值。

// try and find the creator of PHP otherwise return Rasmus Lerdorf
$option = env('PHP_CREATOR', 'Rasmus Lerdorf'); 

覆盖现有环境变量 ( Overwriting Existing Environment Variables )

Sometimes, albeit very rare, an environment might exist and overwrite the one you set in your .env file. To prevent something like this from happening, we can tell DotEnv to overwrite existing environment variables.

有时(尽管非常罕见),可能存在一种环境并覆盖您在.env文件中设置的环境。 为了防止发生这种情况,我们可以告诉DotEnv覆盖现有的环境变量。

$dotenv = new Dotenv\Dotenv(__DIR__, 'new-config-file-name');
$dotenv->overload();

样品申请 ( Sample Application )

The last project I worked on was WordPress based, here is a look at the wp-config.php file.

我从事的最后一个项目是基于WordPress的,下面是wp-config.php文件。

环境变量 变量名 变量值_如何使用环境变量_第3张图片

As you can see, I can add the wp-config file to git without worrying about exposing any sensitive data to the public. I even went as far as to add the database collation to the .env.

如您所见,我可以将wp-config文件添加到git中,而不必担心将任何敏感数据公开给公众。 我什至可以将数据库排序规则添加到.env

结论 ( Conclusion )

By now, I hope you understand environment variables, and why you should use them more often than not in your application.

到现在为止,我希望您了解环境变量,以及为什么应该在应用程序中更多地使用它们。

翻译自: https://scotch.io/tutorials/how-to-use-environment-variables

环境变量 变量名 变量值

你可能感兴趣的:(数据库,java,python,linux,php)