如何只从另一个php文件加载特定的变量?

时间:2014-09-01 10:28:36

标签: php include

在Web服务器的维护脚本中,我需要获取该服务器上每个网站/应用程序的数据库设置。由于大多数网站都基于Drupal,主要设置文件是settings.php,在该文件中定义了各种变量(例如$ database),但有时它还包含该特定站点的ini_set()语句。

该脚本可以包含settings.php来获取数据库设置但是脚本会抛出错误,例如

Warning: ini_set(): A session is active. You cannot change the session module's ini settings at this time in include() (line 123 of /path/to/website/sites/default/settings.php).

有没有办法只从包含的php文件加载(特定)变量? 当然,我的意思是顺利的。我知道,我可以将文件加载到字符串中,使用正则表达式来提取数据库变量和eval(),但我宁愿认为有更好的方法。

1 个答案:

答案 0 :(得分:0)

不是仅包含settings.php(由于包含文件中的ini_set()命令错误,我必须将文件读入字符串,获取所需的部分并eval()

在下面的示例中,我在标准Drupal settings.php

中搜索数据库设置
#include $settings_path; // critical due to ini_set() commands.

$settings = file_get_contents($settings_path); // load file into string
$settings = preg_replace("#/\*.*?\*/#si", '', $settings); // get rid of comments to avoid confusion with preg_match
preg_match('#\$databases.*?;#si', $settings, $dbraw); // get the desired part of the string
eval("\$databases = " . $dbraw[0]); // eval() to create the variable