Last active
September 23, 2022 10:00
-
-
Save mtvbrianking/17b32037406b22e66dff34f2250ddcdc to your computer and use it in GitHub Desktop.
Update settings in dotenv file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
Author
mtvbrianking
commented
Sep 23, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment