【问题标题】:Include Config and Database from other files包括来自其他文件的配置和数据库
【发布时间】:2016-09-07 01:24:13
【问题描述】:

好的,我有一种情况,我在不同的目录中有多个文件,需要弄清楚如何将它们链接在一起。这是结构:

  • /home/username/public_html/index.php
  • /home/username/public_html/secure/index.php
  • /home/username/public_html/elements/includes/db.php
  • /home/username/config.ini

好的,所以在我的两个 index.php 文件中,我都包含引用 db.php:

index.php

<?php include("elements/includes/db.php"); ?>

secure/index.php

<?php include("../elements/includes/db.php"); ?>

现在在 db.php 文件中,我有以下对 config.ini 的引用:

$config = parse_ini_file('../../../config.ini'); 

我知道它没有启动,因为它应该是相对于 index.php 而不是 db.php,但我将如何正确引用这些文件?我希望我的 config.ini 位于 public_html 目录之外。

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    另一种方法是使用魔法常量,例如__DIR__,见Predefinied Constants

    .
    ├── config.ini
    └── public_html
        ├── elements
        │   └── includes
        │       └── db.php
        ├── index.php
        └── secure
            └── index.php
    

    public_html/elements/includes/db.php

    <?php
    
    $config = parse_ini_file(
        __DIR__  . '/../../../config.ini'
    );
    

    public_html/index.php

    <?php
    
    include __DIR__ . '/elements/includes/db.php';
    

    public_html/secure/index.php

    <?php
    
    include __DIR__ . '/../elements/includes/db.php';
    

    注意:我建议使用require 而不是include,请参阅require

    【讨论】:

      【解决方案2】:

      使用$_SERVER['DOCUMENT_ROOT'],这样您就不需要找出每个文件的相对路径:

       $config = parse_ini_file($_SERVER['DOCUMENT_ROOT'].'/../config.ini'); 
      

      【讨论】:

      • 啊哈,我不知道你可以从文档根调用返回...我认为这是使用时的最终位置...谢谢!我试试看。
      • 警告:parse_ini_file(/home/username/public_html./../config.ini): failed to open stream
      • 奇怪的是它在public_html之后的额外时间里抛出了
      • 另外,确保网络服务器用户(可能是 apache)可以读取配置文件
      猜你喜欢
      • 2017-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-08
      相关资源
      最近更新 更多