laravel 修改env内容

 

Laravel 11以上版本的处理逻辑

 // 要更新的环境变量
$updates = [
'APP_LOCALE' => $new_locale,
'APP_FALLBACK_LOCALE' =>$new_locale,
'APP_FAKER_LOCALE' => $new_locale,
];
updateEnv($updates);
function updateEnv(array $values): bool
    {
        $envFile = base_path('.env');

        if (!file_exists($envFile)) {
            return false;
        }

        // 读取当前 .env 内容
        $contents = file_get_contents($envFile);

        // 更新每个指定的值
        foreach ($values as $key => $value) {
            // 转义值中的特殊字符
            $escapedValue = '"' . addcslashes($value, '"') . '"';
            $escapedValue = str_replace('"','',$escapedValue);
            // 替换或添加新的键值对
            if (preg_match("/^{$key}=.*/m", $contents)) {
                $contents = preg_replace(
                    "/^{$key}=.*/m",
                    "{$key}={$escapedValue}",
                    $contents
                );
            } else {
                $contents .= PHP_EOL . "{$key}={$escapedValue}";
            }
        }

        // 写入文件
        return file_put_contents($envFile, $contents) !== false;
    }

低版本

/**
 * 更新.env文件
 */
if (!function_exists('DJ_help_update_env')){
    function DJ_help_update_env($array = null){
        if ($array == null) {
            return false;
        }
        $envPath = base_path() . DIRECTORY_SEPARATOR . '.env';
        $contentArray = collect(file($envPath, FILE_IGNORE_NEW_LINES));

        foreach ($contentArray as $key => $value) {
            if ($value == '') {
                $key = '';
            } else {
                $cont = explode('=', $value);
                if (array_key_exists($cont[0], $array)) {
                    $contentArray[$key] = $cont[0] . '=' . $array[$cont[0]];
                } else {
                    $contentArray[$key] = $cont[0] . '=' . $cont[1];
                }
            }
        }
        $content = implode("\n", $contentArray->toArray());
        if (\File::put($envPath, $content)) {
            return true;
        }
        return false;
    }

 

posted @ 2026-01-30 18:27  豆浆浆  阅读(3)  评论(0)    收藏  举报