包括其他文件中的配置和数据库 [英] Include Config and Database from other files

查看:44
本文介绍了包括其他文件中的配置和数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Ok, I have a situation where I have several files in different directories and need to figure out how to link them all together. Here is the structure:

  • /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:

Ok, so in both of my index.php files i have this include referencing db.php:

index.php

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

secure/index.php

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

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

Now inside of the db.php file, I have the following reference to config.ini:

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

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

I know its not picking up because it should be relative to index.php instead of db.php, but how would I reference these files correctly? I want my config.ini to be outside of the public_html directory.

推荐答案

一种替代方法是使用魔术常数,例如__DIR__,请参见预定义常量.

An alternative is to use magic constants e.g. __DIR__, see 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,请参见要求.

Note: I recommend using require instead of include, see require.

这篇关于包括其他文件中的配置和数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆