code-8
code-8

Reputation: 58632

Update .env value using PHP

I know some of your might think that this will lead to security issue. 🔐 🐞

But ...

I only want to update only 2 specific flags, because sometimes, I want to see the reports, and sometimes, I don't. If I have a way to update those flags -- I can just hook up a route to toggle that functionality - via Apple iPhone Shortcut whenever I want to see reports via EMAIL or SMS.


I've tried

created a route

Route::get('/env/{flag}/{value}','GeneralController@envUpdate');

called it

http://localhost/env/MAIL_REPORT/false

that will trigger this function

public function setEnv($key, $val)
{
    $path = base_path('.env');

    if (file_exists($path)) {

        file_put_contents($path, str_replace(
            $key . '=' . env($key), $key . '=' . $val, file_get_contents($path)
        ));
    }
}

public function envUpdate($flag,$value)
{
    //dd($flag,$value);
    $allow_flags = ["MAIL_REPORT", "SMS_REPORT"];

    if (in_array($flag, $allow_flags))
    {
        setEnv((string)$flag, (string)$value);
        return env(env((string)$flag));
    }

} 

I kept getting true because in my .env does not seem to be updated

MAIL_REPORT=true

I suppose to have MAIL_REPORT=false

Note : I already ran : sudo chmod 777 .env

How would one go about and debug this further?

Upvotes: 1

Views: 3191

Answers (1)

Dees Oomens
Dees Oomens

Reputation: 5082

If you need to change the environment variables I would suggest to just change your .env file and re-cache your config (if in production). Your current implementation might be pretty sensitive for security issues.

If you do want to change your env variables programmatically at run time you can always use the config() helper method.

config(['mailing. reporting' => false]);

This is also documented in the docs.

Edit

So I think you're implementation of the env variables might be a little incorrect. The environment variables itself SHOULD NOT change at run time in your applications. The only place where the env() function should be called is in the config files (found in the config directory). So what you want is to create a new key in your config/mailing.php config file.

'reporting' => env('MAIL_REPORT', false),

Now whenever you need to set this variable to true you can either change the .env file or use the first given example (config(['mailing. reporting' => false]);).

Read more about it in the docs.

Upvotes: 2

Related Questions