1

I am building an installer script in my application. I am declaring some constants in one file for example

define(DB, '');
define(USER, '');
define(PASS, '');
define(HOST, ''); 

Now I want to access this DB variable first and update the value of DB and so on.

I have tried so far is this

define(DB, '%dbname');
define(USER, '%dbuser');
define(PASS, '%dbpass');
define(HOST, '%dbhost'); 

$file_path = "constant.php";
$dbname = $_POST['dbname'];
$value = "%dbname";
$replace_with = $value;
$content = file_get_contents($file_path);
$content_chunks = explode($string_to_replace, $content);
$content = implode($replace_with, $content_chunks);
file_put_contents($file_path, $content);

This script works fine. But the only issue is that once its update the value it can't update the value again. The value cannot be updated twice because the script was checking this value %dbname. Now since it has been changed to some value. I can't be able to update the value again. I want to do something like detect the variable DB then update the value in front of it.

mynameisbutt
  • 167
  • 1
  • 3
  • 22
  • 1
    An alternative solution could be to generate a json-file with the credentials and then have your `constant.php` file read that file and set the constants from it. Your current script is very error prone and would break if someone have a password containing, for example, `'` since it would generate invalid syntax like: `define(PASS, 'foo'bar')`. There are more cases that would cause issue though. – M. Eriksson May 04 '21 at 09:25
  • This seems like you should go for an actual config file (a non-PHP format, like YAML or JSON or an `.ini` file...), rather than trying to programatically change PHP code. Have a look at [this question](https://stackoverflow.com/questions/14752470/creating-a-config-file-in-php). – El_Vanja May 04 '21 at 09:25

0 Answers0