Search code examples
phprequire

issues requiring files in php from multiple locations


I have a single PHP file that i require in many different php files.

The PHP file stores DB info and also requires another file called something.php....

Now, say I stored the PHP file (with db info) called my_db_info.php in a folder called config.

I then have another PHP file that was stored in two folders above the config folder, called all_functions. Now to require the file with db info I'd write require('folder1/config/my_db_info.php'); Now this would require my_db_info.php fine but the file required in my_db_info.php (something.php) will not be included which will cause a fatal error.

so when I test the php in the all_functions folder, i get a fatal error telling me that the file (something.php) required in the actual db file (my_db_info.php) could not be found.

then, when I alter the my_db_info.php file and change the require line to decrease how many folders it goes up or down, example:

require('../something.php');

To

require('../../something.php');

It seems to work. But i have to change the folder up/down count to what the main file (in the all_functions folder) is. so as if i was requiring something.php in that file...

Which means, when i want to require my_db_info.php into another file, which is in a completely different location to the file in the all_functions folder (5 folders up for example), I will have to make another my_db_info.php for it to all work properly....

Why does this happen, and is there any way I can fix this?

Thanks


Solution

  • To me, it seems the easiest thing for you to do, is the directly include the PHP files rather than giving the relative path (which is how you're including them).

    Try using $_SERVER['DOCUMENT_ROOT'] (which will give you something like /home/username/htdocs)

    If I understand your setup correctly, you have the following 2 directories in a directory (possibly in the root):

    /
    /all_functions
    /config
    

    The instead of including with multiple include("../my_db_info.php"); change to include($_SERVER['DOCUMENT_ROOT']."/config/my_db_info.php"); and repeat as needed be for other directories.

    If you do it this way, it will work for multiple directories away from where the config+all_functions directories are located.

    Edit (in response to comment)

    If $_SERVER['DOCUMENT_ROOT'] is unavailable, then you could always manually write the document root, then define it as a constant, then call it in each script.

    Eg.

    define(rootpath, "/home/username/htdocs");
    include(rootpath."/config/my_db_info.php");
    

    Then you can use rootpath as your defined constant in my_db_info.php (etc) if needed be, the downside is that you'd have to write this in every script - though fingers crossed that $_SERVER['DOCUMENT_ROOT'] is available for you.