永久保存php变量,无需数据库

发布于 2024-09-12 00:56:50 字数 154 浏览 2 评论 0原文

在我网站的管理区域中有一个表单,用于填写网站使用的 mysql 数据库的主机名、用户名和密码。目前这些值被硬编码到 php 类中。但是我可以链接谁,以便表单可以编辑 php 类中的变量(并将结果保留在服务器上,换句话说,变量是硬编码的)。我通常会将这样的东西保存在数据库中,但显然这是不可能的。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

那些过往 2024-09-19 00:56:50

创建一个配置文件,并授予您的 Web 服务器对其的写入权限。然后只需编写一个脚本将数据库配置保存到该文件即可。例如

$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);

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);
回忆躺在深渊里 2024-09-19 00:56:50

将值保存在配置文件中。并确保它无法从网络访问。

最简单的解决方案是将值保留在配置数组中 - 用户输入值,从中生成一个数组,然后 file_put_contents("config.php", "。使用此方法,每当您需要配置数组时,您所需要做的就是include config.php,它就在那里。

这是未经测试的代码,仅用于示例目的。根据您的情况,您可能需要解决竞争条件,file_put_contents 还不够。上面代码的要点是: var_export 返回有效的 php 代码,您可以 eval (如果您足够邪恶)或回显到文件并稍后包含该代码。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文