How to modify .env in laravel: 1. Obtain the path of the env file through "base_path('.env');"; 2. Declare through "function updateEnv($data = array()){}" Function; 3. Modify and parse the env file through "$pattern = '/([^\=]*)\=[^\n]*/';" regular matching.
The operating environment of this tutorial: Windows 7 system, Laravel version 5.7, Dell G3 computer.
How to modify .env in laravel?
Laravel dynamically modifies the value of the env environment variable!
Introduction
In order to separate the configuration parameters to distinguish the development environment, online environment and other functions, or manually switch the cache driver, queue driver, mail server address, Etc., etc., these can be easily labeled. So laravel uses .env files to wrap these configuration data, which are key-value pairs.
Learning time
Under normal circumstances, we are not allowed to modify the content of the env file unless it is processed manually. However, in programming, it is inevitable to encounter situations that must be modified. So how to dynamically operate the key-value pairs in the env file?
Assume that the APP_KEY generated by the system using key:generate is not safe. When doing automated deployment and batch deployment, there is a need to dynamically modify the APP_KEY key. How to achieve this?
In fact, the env file is just a text file, written in a standard format such as key=value, using string matching throughout, with a single line until the newline character stops.
Then modifying the content of the env file is nothing more than finding the relevant key and then replacing the value, that's it.
The first version is given below, which is the simple and crude file_put_contents. First get the path of the env file:
$path = base_path('.env');
Need to determine whether the file exists:
if (file_exists($path)){ // 文件存在 }
The file exists Then first read all the contents of the file into a string variable:
$origin = file_get_contents($path);
Assume that our new APP_KEY exists in the variable $new_key, first get the original APP_KEY value:
$old_key = env('APP_KEY');
String Of course, the operation requires direct matching using the string replacement function. We use str_replace. After all, the amount of data in the env file is not large, so there is no big performance problem.
$result = str_replace('APP_KEY=' . $old_key, $new_key, $origin);
In this way, the value of the latest env file is stored in $result. Then just write the env file:
file_put_contents($result);
The default is to overwrite, so after executing the program, the env file will be The latest dynamically modified data.
Go deeper
The above code is still flawed, because there is basically no error handling, which can easily cause errors. In addition, for file operations as important as env, directly using string replacement to read and overwrite the entire file is inherently risky.
How to transform our operation methods to make them safer? We need more compatible code. In this section, we try to use regular matching to parse the env file, read it line by line, operate it line by line, and judge it line by line. If the key value exists, it will be overwritten; if it does not exist, it will be created. In this way, it can be compatible with both new and update functions, and the supported key values are more flexible.
Encapsulated as a helper function, assuming that the parameter passed in is an array and an associative array. Declare the function as follows:
function updateEnv($data = array()){}
Writing logic in the function body, first check if it is not empty:
if (! count($data)) {return;}
If it is not an associative array, it is also not accepted, because the env file must clearly specify the key and value. For associative arrays, you only need to determine that the keys of the array are different from the automatically serialized keys:
if (array_keys($data) === range(0, count($data) - 1)) {return;}
Prepare the matching pattern:
$pattern = '/([^\=]*)\=[^\n]*/';
This is the format for writing the env file. We have already introduced it in the previous section. We read the old env file into an array and declare a new array to store the latest configuration file data:
$envFile = base_path() . '/.env'; $lines = file($envFile); $newLines = [];
Then traverse the old file data and parse it line by line:
foreach ($lines as $line) { preg_match($pattern, $line, $matches); if (!count($matches)) { $newLines[] = $line; continue; } if (!key_exists(trim($matches[1]), $data)) { $newLines[] = $line; continue; } $line = trim($matches[1]) . "={$data[trim($matches[1])]}\n"; $newLines[] = $line; }
Above This is just a rough processing flow. This parsing process can be independently customized as a custom function or other parsing engines, so it is universal.
Finally, write the new parsed data completely into the env file:
$newContent = implode('', $newLines); file_put_contents($envFile, $newContent);
At this point, the update operation of the env file is completed.
Written at the end
This article implements the function of dynamically creating and updating env global configuration file data in the program in two ways. The second method has better fault tolerance and versatility. , has strong scalability, so we recommend it. The first approach has no error handling and is almost unusable in a production environment. It would be great if everyone knew the idea.
Recommended learning: "laravel video tutorial"
The above is the detailed content of How to modify .env in laravel. For more information, please follow other related articles on the PHP Chinese website!