【问题标题】:How to load only a specific variable from another php file?如何仅从另一个 php 文件加载特定变量?
【发布时间】:2014-09-01 10:28:35
【问题描述】:

在 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(),但我宁愿认为有更好的方法。

【问题讨论】:

  • 最明智的做法是将这些变量放入第三个文件中,您需要在两个文件中include
  • 确实如此。但我确实需要从各种不同的系统(Drupal、LimeSurvey、CodeIgniter、自定义系统)读取设置,总共有 100 多个安装。对于自定义站点,这确实是一个选项(实际上是这样设置的),但是对于 Drupal 等预定义系统,我希望有一个不需要更改安装例程的解决方案。

标签: php include


【解决方案1】:

不只是包含 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 2021-09-08
    相关资源
    最近更新 更多