简体   繁体   中英

Make a PHP configuration file

I'm trying to make a simple PHP settings file. It works like this:

<?php //settings.php
    $setting1 = "Something";
    $setting2 = "somethingelse";
?>

I then have an html form that get's submitted to another file, What i'm curious about, Is how to change the settings in "settings.php" to the data submitted in the form and then save the file.. If that's even possible. I do know one method would be

  1. Include settings.php
  2. Change the settings accordingly
  3. Delete settings.php
  4. Recreate the string for settings.php file
  5. Write the string out to a new settings.php file

But i'm wondering if there's a simpler method.. Because my settings.php is pretty lengthy.. Any help would be great :3 And if this is a stupid question, I apologize. I'm just curious as to weather or not there is a way to do this. Thanks in advance!

Edit

After having four years to reflect and grow, I've found that this idea is insane. If you want to manage a configuration, the best way to go (imho) would be using an array include file. The configuration should never be modified (which I had requested in points 2., 3., 4., and 5.

If you're looking for a more in depth configuration library, take a look at Gestalt , a library written by a colleague of mine.

Example

// main.php
<?php
    $config = include_once 'config.php';

    echo 'Configured name is: ' . $config['main']['name'];

// config.php
<?php
    return [
        'main' => [
            'name' => 'Nathan'
        ]
    ];

It's not necessarily a stupid question, but it's an incredibly stupid idea.

Consider someone submitting the form with value "rmdir('/');".

If you really want to do something like this, you'd be better off using something like JSON that isn't executeable.

Does settings.php needed to be a .php file? If not, you could create a form like so:

<form id="settings" action="submit.php" method="post">
Setting one: <input type="text" name="set1" value="" width="10" ><br />
Setting Two: <input type="text" name="set2" value="" width="10"><br />
    Setting Three: <input type="text" name="set3" value="" width="10"><br />
<input type="submit" value="Submit settings"  >
</form>

Then create a "submit.php" to write the files to the server in a usable format:

$filename = $_POST['filename'] . '.csv';
$export = $_POST['export'];
$writer = fopen($filename, 'w') or die('cannot create');
fwrite($writer, $export . "\n");
fclose($writer);

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.basename($filename));
readfile($filename);
unlink($filename);

exit();

I think that should suit your purposes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM