Brandon S
Brandon S

Reputation: 1

Include Config and Database from other files

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:

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

index.php

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

and secure/index.php

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

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

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

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.

Upvotes: 0

Views: 382

Answers (2)

Gerard Roche
Gerard Roche

Reputation: 6361

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';

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

Upvotes: 1

aynber
aynber

Reputation: 23011

Use $_SERVER['DOCUMENT_ROOT'] so that you don't need to figure out relative paths on each file:

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

Upvotes: 0

Related Questions