0

my question is similiar like this : Replace string in text file using PHP

but i want replace by spesification variable for example, i have already file exist .env

variable_1=data_2021
variable_99=data_2050
variable_991=data_2061

so how i can replace by spesificiation name variable for the value ? i want replace data_2050 with data_2051 without change on other text where the variable is variable_99

        $myfile = fopen("../../.env.securepay", "w") or die("Unable to open file!");
        fwrite($myfile, 'variable_99='.$value);
        fclose($myfile);

        // $myfile = fopen("../../.env", "w") or die("Unable to open file!");
        // fseek($myfile, 0);
        // fwrite($myfile, 'variable_99 ='.$value);
        // fclose($myfile);

        // $oldMessage = 'variable_99';
        // $deletedFormat = '';

        // //read the entire string
        // $str=file_get_contents('../../.env.securepay');

        // //replace something in the file string - this is a VERY simple example
        // $str=str_replace($oldMessage, $deletedFormat, $str);

        // //write the entire string
        // file_put_contents('../../.env', $str);

above code just remove all the content file .env and re added variable_99=value

Yogi Arif Widodo
  • 563
  • 6
  • 22

1 Answers1

0

You can use file_put_contents and parse_ini_file like this follow below

function modifyEnv($path,$values = []) {
    $env = [];
    foreach(parse_ini_file($path) as $k => $value) {
        if(in_array($k,array_keys($values))) {
            $env[$k] = "$k={$values[$k]}";
        }
    }
    return file_put_contents($path,implode(PHP_EOL,$env));
}

Then you can call like this, you can replace multiple .env variables by using array key, value. key is the old value and the value is the new value

modifyEnv('../../.env.securepay',[
    'variable_99' => 'data_2051',
    'variable_1' => 'data_2051'
]);
Jerson
  • 1,700
  • 2
  • 10
  • 14
  • ``` 'variable_99' => 'variable_99=data_2051' ``` but my conditions i dont know my value, so when i try the code the output is ```variable_1=data_2021 variable_99=data_2051=data_2050``` – Yogi Arif Widodo Aug 06 '21 at 06:13
  • the code still replace all string , my question is `without change on other text ` so i only want to change some variable only, for example is variable_99. other variable is constanta. – Yogi Arif Widodo Aug 06 '21 at 22:13