save php variables permanently without database
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 variab开发者_JAVA技巧les 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.
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);
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.
精彩评论