Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何通过控制器更改Laravel6.0中的.env变量?_Php_Laravel - Fatal编程技术网

Php 如何通过控制器更改Laravel6.0中的.env变量?

Php 如何通过控制器更改Laravel6.0中的.env变量?,php,laravel,Php,Laravel,我正在Laravel上制作一个系统,在那里我想授予管理员更改一些.env变量(如邮件设置(服务器或端口)等)的权限。我该怎么做 我已经为相同的内容创建了一个方法changeev: public function changeEnv($data = array()){ if(count($data) > 0){ // Read .env-file $env = file_get_contents(base_path() . '/.env');

我正在Laravel上制作一个系统,在那里我想授予管理员更改一些.env变量(如邮件设置(服务器或端口)等)的权限。我该怎么做

我已经为相同的内容创建了一个方法
changeev

public function changeEnv($data = array()){
      if(count($data) > 0){

        // Read .env-file
        $env = file_get_contents(base_path() . '/.env');

        // Split string on every " " and write into array
        $env = preg_split('/\s+/', $env);;

        // Loop through given data
        foreach((array)$data as $key => $value){

          // Loop through .env-data
          foreach($env as $env_key => $env_value){

            // Turn the value into an array and stop after the first split
            // So it's not possible to split e.g. the App-Key by accident
            $entry = explode("=", $env_value, 2);

            // Check, if new key fits the actual .env-key
            if($entry[0] == $key){
              // If yes, overwrite it with the new one
              $env[$env_key] = $key . "=" . $value;
            } else {
              // If not, keep the old one
              $env[$env_key] = $env_value;
            }
          }
        }

        // Turn the array back to an String
        $env = implode("\n", $env);

        // And overwrite the .env with the new data
        file_put_contents(base_path() . '/.env', $env);

        return true;
      } else {
        return false;
      }
    }

用法:

$this->changeEnv(['lastEvaluatedKeyAU' => 'randomID-or-randomString']);

如何填充$data?只需将键值对作为数组传递即可。您永远不应该出于任何原因以编程方式修改
.env
文件。这是一个静态可缓存资源。我需要根据他/她在表单中输入的用户值填充数组。我应该在哪个变量中输入相应的值。例如,如果我从用户处读取邮件端口,我应该将其放入$data['MAIL\u PORT']?我知道DigitalDriver。但这是一个要求,所以我必须这样做。临时的还是永久的?