Skip to content

Instantly share code, notes, and snippets.

@mtvbrianking
Last active September 23, 2022 10:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtvbrianking/17b32037406b22e66dff34f2250ddcdc to your computer and use it in GitHub Desktop.
Save mtvbrianking/17b32037406b22e66dff34f2250ddcdc to your computer and use it in GitHub Desktop.
Update settings in dotenv file
<?php
function saveToEnvFile(string $dotEnv, string $pattern, string $label, ?string $value): bool
{
$readFrom = fopen($dotEnv, 'r');
$writeTo = tmpfile();
$isDirty = false;
while (!feof($readFrom)) {
$line = fgets($readFrom);
$setting = "{$label}=\"{$value}\"";
$newLine = preg_replace($pattern, $setting, $line);
if ($newLine != $line) {
$isDirty = true;
}
fputs($writeTo, $newLine);
}
$tmpDotEnv = stream_get_meta_data($writeTo)['uri'];
if ($isDirty) {
rename($tmpDotEnv, $dotEnv);
} else {
unlink($tmpDotEnv);
}
fclose($readFrom);
fclose($writeTo);
return $isDirty;
}
@mtvbrianking
Copy link
Author

$dotEnv = '/var/www/example/.env';
$pattern = "/^{$label}=[\"']?.*/";
$label = 'APP_URL';
$value = 'https://example.local';

$isDirty = saveToEnvFile($dotEnv, $pattern, $label, $value);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment