永久保存php变量,无需数据库
在我网站的管理区域中有一个表单,用于填写网站使用的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
创建一个配置文件,并授予您的 Web 服务器对其的写入权限。然后只需编写一个脚本将数据库配置保存到该文件即可。例如
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.
将值保存在配置文件中。并确保它无法从网络访问。
最简单的解决方案是将值保留在配置数组中 - 用户输入值,从中生成一个数组,然后 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 isinclude 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 caneval
(if you're evil enough) or echo to a file and include that later.