In the admin area of my site there is a form which is for the hostname, username and password for the mysql database that the site uses. Currently these values are hardcoded into a php class. But who can I link it so the form can edit the variables in the php class (and keep the results on the server, in other words the variables are hardcoded). I'd normally keep things like this in a database but obviously this can't be done.
-
possible duplicate of [PHP, Reading File](http://stackoverflow.com/questions/2237291/php-reading-file) – Gordon Jul 25 '10 at 10:09
-
1oh, don't be so pedantic, this is about writing, not reading files. – Jonathan. Jul 25 '10 at 10:32
2 Answers
Create a configuration file, and grant your web server write access to it. Then it's just a simple matter of writing a script which saves the DB config to this file. E.g.
$fh = fopen('config.php', 'w');
fwrite($fh, chr(60) . "?php\n");
fwrite($fh, sprintf("define('DB_HOST', '%s');\n", addslashes($_POST['DB_HOST'])));
fwrite($fh, sprintf("define('DB_USER', '%s');\n", addslashes($_POST['DB_USER'])));
fwrite($fh, sprintf("define('DB_PASS', '%s');\n", addslashes($_POST['DB_PASS'])));
fclose($fh);

- 5,399
- 27
- 29
-
how does this work then if I want to modify it once I created the config file for the first time. – Jonathan. Jul 25 '10 at 09:45
-
You'll put the config file creation code in another script say, editconfig.php. – jmz Jul 25 '10 at 10:38
Keep the values in a config file. And make sure it is not accessible from the web.
The easiest solution is to keep the values in a configuration array - the user enters the values, you generate an array from it, then file_put_contents("config.php", "<?php $config = " . var_export($config))
. With this method whenever you need the config array, all you need to do is include config.php
and it's there.
This is untested code, for example purposes only. Depending on your situation, you may need to solve race conditions, file_put_contents
is not enought for that. The main point of the above code is: var_export
returns valid php code, that you can eval
(if you're evil enough) or echo to a file and include that later.

- 33,687
- 18
- 94
- 85
-
how does this work then if I want to modify it once I created the config file for the first time. – Jonathan. Jul 25 '10 at 09:55
-
@Jonathan You modify the already loaded `$config` array, then do the `file_put_contents` part again. – Maerlyn Jul 25 '10 at 10:03