由于各种问题,动态配置环境变量不一定好使,于是写了个~ /** * 动态配置.env环境变量 * * @param string $key 变量名 支持组 * @param string $value 变量值 * @return void */ public function setEnv(string $key = '', string $value = '') { $file = root_path() . '.env'; $data = ''; if (is_file($file)) { $data = trim(file_get_contents($file)); } if ($data == '') { // 没有内容就直接创建 $data = <<<Env APP_DEBUG = false [APP] DEFAULT_TIMEZONE = Asia/Shanghai [DATABASE] TYPE = mysql HOSTNAME = HOSTPORT = 3306 USERNAME = PASSWORD = DATABASE = PREFIX = CHARSET = utf8 DEBUG = true [LANG] default_lang = zh-cn [REDIS] REDIS_HOSTNAME = PORT = 6379 REDIS_PASSWORD = SELECT = 0 [QUEUE] QUEUE_NAME =Env; } // 修改配置 $key = strtoupper($key); if (strpos($key, '.')) { $arr = explode('.', $key, 2); $key1 = $arr[0]; $key2 = $arr[1]; $start = mb_strpos($data, '[' . $key1 . ']'); if ($start !== false) { // 找到配置组 $str_up = mb_substr($data, 0, $start); $str_lower = mb_substr($data, $start); if (preg_match('/' . $key2 . ' =/', $str_lower)) { // 找到就直接替换 $str_lower = preg_replace('/(\n' . $key2 . ' =(.*)|\n' . $key2 . ' =)/', "\n" . $key2 . ' = ' . $value, $str_lower); $data = $str_up . $str_lower; } else { // 未找到直接在组下面追加 $str_q = '/\[' . $key1 . '\]/'; $str_h = "\[" . $key1 . "\]\n" . $key2 . " = " . $value; $str_lower = preg_replace($str_q, $str_h, $str_lower); $data = $str_up . $str_lower; } } else { // 未找到配置组 追加 $data = $data . "\n[" . $key1 . "]\n" . $key2 . " = " . $value; } } else { // 说明是顶层配置 if (preg_match('/' . $key . ' =/', $data)) { // 直接替换数据 $data = preg_replace('/([\n]{0,1}' . $key . ' = (.*)|[\n]{0,1}' . $key . ' =)/', "\n" . $key . ' = ' . $value, $data); } else { // 追加 $data = $key . " = " . $value . "\n" . $data; } } file_put_contents($file, $data); }