diff --git a/src/Illuminate/Support/Env.php b/src/Illuminate/Support/Env.php index 85dc13415a65..01747846ffa5 100644 --- a/src/Illuminate/Support/Env.php +++ b/src/Illuminate/Support/Env.php @@ -191,12 +191,11 @@ protected static function addVariableToEnvContents(string $key, mixed $value, ar $shouldQuote = preg_match('/^[a-zA-z0-9]+$/', $value) === 0; $lineToAddVariations = [ - $key.'='.(is_string($value) ? '"'.addslashes($value).'"' : $value), - $key.'='.(is_string($value) ? "'".addslashes($value)."'" : $value), + $key.'='.(is_string($value) ? self::prepareQuotedValue($value) : $value), $key.'='.$value, ]; - $lineToAdd = $shouldQuote ? $lineToAddVariations[0] : $lineToAddVariations[2]; + $lineToAdd = $shouldQuote ? $lineToAddVariations[0] : $lineToAddVariations[1]; if ($value === '') { $lineToAdd = $key.'='; @@ -277,4 +276,35 @@ protected static function getOption($key) return $value; }); } + + /** + * Wrap a string in quotes, choosing double or single quotes. + * + * @param string $input + * @return string + */ + protected static function prepareQuotedValue(string $input) + { + return strpos($input, '"') !== false + ? "'".self::addSlashesExceptFor($input, ['"'])."'" + : '"'.self::addSlashesExceptFor($input, ["'"]).'"'; + } + + /** + * Escape a string using addslashes, excluding the specified characters from being escaped. + * + * @param string $value + * @param array $except + * @return string + */ + protected static function addSlashesExceptFor(string $value, array $except = []) + { + $escaped = addslashes($value); + + foreach ($except as $character) { + $escaped = str_replace('\\'.$character, $character, $escaped); + } + + return $escaped; + } }