0

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

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.

2 Answers2

1

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.

Gerard Roche
  • 6,162
  • 4
  • 43
  • 69
0

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'); 
aynber
  • 22,380
  • 8
  • 50
  • 63
  • ahhh, i didnt know you could go backward from a document root call... i thought that was the final location when used... thank you!!! I'll give it a try. – Brandon S Sep 06 '16 at 16:50
  • Warning: parse_ini_file(/home/username/public_html./../config.ini): failed to open stream <--- could not get it to reference a directory back... tried a few variations: ($_SERVER['DOCUMENT_ROOT'].'../config.ini') – Brandon S Sep 06 '16 at 16:53
  • Odd that it's throwing in the extra period after `public_html` – aynber Sep 06 '16 at 17:00
  • Also, make sure the config file is readable by the web server user (possibly apache) – aynber Sep 06 '16 at 17:01