How to edit php file variables with another php file

Ok, so I want to do something similar to how Simple Machine Forum edits some variable in the forum admin panel. For example I have a settings.php file . I want tool.php to open and find all declared php variables in settings.php , for example $ background_color = 'Orange' and output to tools.php Background color: orange inside the form tag, which after changing to "Purple" and sent replaces " Orange " to 'Purple' and now if I open 'settings.php' the variable inside the file is now " $ background_color = 'Purple' "without having to go manually, edit it. I can simply submit new data to a variable and replace the old ones.

+3


source to share


3 answers


To keep the data persistent, you will need to store the data in a database or a separate file, for example. JSON file. Then you can use this data wherever you need it.

Here's an example using a JSON file.

setting_variables.json:

{
    "background": "red",
    "color": "white"
}

      



settings.php

$settings = json_decode(file_get_contents("settings_variables.json"), true);
$background = $settings['background'];

      

tools.php

include ("settings.php");

// If form is posted
if(isset($_POST['submit'])){
    /* Updating variables in JSON file*/

    //Get settings_json file
    $setting_vars = json_decode(file_get_contents('settings_variables.json'), true);

    // Update variable
    $background = $setting_vars['background'] = $_POST['color'];

    // Store variable value to JSON file
    file_put_contents("settings_variables.json", json_encode($setting_vars));
}

?>

<form method="post" <?php echo "style='background-color:".$background . "'"; ?>>
    <select name="color">
    <option value="red">red</option>
    <option value="blue">blue</option>
    <option value="orange">orange</option>
    <option value="yellow">yellow</option>
    <option value="purple">purple</option>
  </select>
  <input type="submit" name="submit"/>
</form>

      

+1


source


You can do it with a database select this value from the database in settings.php and update this with your tools.php or wherever you like.



0


source


To load variables into tool.php is simple include("settings.php")

.

To change your settings, you will need to change settings.php.

The easiest way to do this should be with regex - replacing the old value with a new one, for example. ["\$background_color *= *'\d*'"]

and replace it with ["\$background_color = 'Purple'"]

.

Just overwrite the file with a new line.

I'm not sure if I escaped correctly, but this way you should be able to replace the entire file.

See http://php.net/manual/en/function.preg-replace.php

The downside is that if the settings file is very large, this may take a while, although this probably won't be a problem for your use case.

alternatively, you can read the file line by line and replace it (either manually or again with a regular expression).

0


source







All Articles