Best way to include config.php

Hi,
I’ve got a file config.php with database connection, ho do I include to my pages? At the moment i’m doing this:
…/config.php
…/…/config.php
Is there a more elegant way of doing it?
Many thanks

I typically use

realpath(__DIR__);

This way, you get the actual realpath to the current file. I typically set a constants on the index file using that. So if you do it correctly, you should get

/var/www/html/random_directory

After that, all you’d really need to do is something like

require_once(ROOT . '/config.php');

Which should give you

/var/www/html/random_directory/config.php

It should also work for subdirectories and sub files.

1 Like

I would advise against using realpath in this case because this function must consult the file system in order to return the pathname, which adds some overhead. __DIR__ alone is sufficient because it returns absolute pathname itself so the realpath() function is redundant.

One thing to note is that you can use relative paths following an absolute path so if you assign your ROOT constant somewhere deeper in the directory tree you can define a directory one level up (or more) in this way:

define('ROOT', __DIR__ . '/..');
...
require_once(ROOT . '/config.php');

which can be equivalent to

require_once('/var/www/html/random_directory/../config.php');

which is the same as

require_once('/var/www/html/config.php');

and will work just fine.

2 Likes

Hi in my index.php at the moment i’ve got the login module I believe is still fine to set the path here, is it correct?

It really doesn’t matter. If any file you want to include is not within the directory you set the path to, then adding the constant to the file should be required. So if your login module is within the same folder as your index file, you really don’t have to use the constant to define the path. But say your login module is within another folder and is being required from a controller that’s being instantiated from your index, using the constant path should be used in case the path you define to include the login module might break. Just a fruitful thought.

I don’t remember the specifics now but specifying the full path (like with a constant) is preferred because when a php script is run via command line then the current working directory may be different and then relative paths may break. Cron jobs often run scripts in the command line environment. I didn’t understand why most php frameworks and libraries always use absolute paths until my scripts broke when run with a cron job. So now just in case I always either use __DIR__ or define my own constants with path so as to avoid relative paths.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.