CodeIgniter Forums
How to set variable in .env file programity - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: How to set variable in .env file programity (/showthread.php?tid=77876)



How to set variable in .env file programity - shafiei777 - 10-29-2020

Hello,
I want to set database variable and some custom variable like license key to my .env file programmity. How can I do that?


RE: How to set variable in .env file programity - Chivinsdev - 04-17-2023

Hello friend,
Use this small snippet I wrote. I hope it will do exactly what you want I am currently using it in my premium script.

PHP Code:
if (!function_exists('set_env')) {
    function set_env($key$value)
    {
        $path ROOTPATH '.env';

        $content file_get_contents($path);

        if (!str_contains($content$key)) {

            $content "\n" "$key = " $value;
        }

        file_put_contents($pathstr_contains($content'# ' $key) ? str_replace('# ' $key$key$content) : $content);

        $content file_get_contents($path);

        if (is_bool(env($key))) {
            $old env($key) ? 'true' 'false';
        } elseif (env($key) === null) {
            $old 'null';
        } else {
            $old env($key);
        }

        $content str_replace("$key = " $old"$key = " $value$content);

        if (file_exists($path)) {
            file_put_contents($path$content);
        }
    }