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
  • 5,359
  • 4
  • 39
  • 65
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
  • 20,647
  • 8
  • 49
  • 57