user3790186
user3790186

Reputation: 269

Overwrite an existing php variable value in a file using php

I have a file named config.php with several variable configuration values including the following one:

$config['currencyCode'] = 'USD';

I need to open config.php file and change the value of $config['currencyCode'] to another value and save it.

Is it possible via php using fopen or some other manner? Changing a specific variable value in the file?

Upvotes: 1

Views: 1849

Answers (3)

Jacques Marais
Jacques Marais

Reputation: 2756

Simply replace the value by reading the file contents, replacing the value you want, and writing it back into the file:

$file = 'config.php';
$contents = file_get_contents($file);
$contents = str_replace("$['currencyCode'] = 'USD';", "$['currencyCode'] = 'GBP';", $contents);
file_put_contents($file, $contents);

Upvotes: 0

Sumeet Sadarangani
Sumeet Sadarangani

Reputation: 76

You can simply store the value of currencyCode in database and can retrieve it in config file as per the below code.

$select = mysqli_query($connection, "SELECT currencyCode FROM tablename");
$row = mysqli_fetch_assoc($select);
echo $row['currencyCode'];

Also you can update the value of currencyCode in database with below query.

mysqli_query($connection, "UPDATE tablename SET currencyCode = [value]");

Upvotes: 1

Alex
Alex

Reputation: 1573

Is it necessary?

// config.php
$config['currencyCode'] = 'USD';

// shop.php
require 'config.php';
// can alter the value if you want to
$config['currencyCode'] = 'GBP';

It will not change the value in config.php, but you can override it if you want to, which is probably better

Upvotes: 1

Related Questions