Question

I am trying to get my include() functions in order but everytime I switch the syntax in one directory it messes up its subdirectory and vice versa.

I have a file called 'header.php' in my 'localhost/FTS/includes/header.php' folder. The 'FTS' folder has my index.php file so it is technically my root folder while I am testing.

In the file 'localhost/FTS/admin.php' I use the line include 'includes/header.php'; and it works fine but then when I go into the file 'localhost/FTS/admin/members.php' the include file is not found. Also inside of my 'header.php' file I include a couple more files from my root directory.

I just want all of my includes to work from each directory. Any ideas?

Was it helpful?

Solution

The include statement includes files relative to the script executing include, which is why you're seeing this issue. You have a couple of options available to you:

  • You can preface your include path with something like $_SERVER['DOCUMENT_ROOT'], which if you're using Apache, will reference your document root directory. So something like include( $_SERVER['DOCUMENT_ROOT'] . "/includes/header.php" ); will appear to the script as an absolute path, so it will work if called from various places in your structure, but still be portable (note that it would require being called from a web server, this won't work if you're using your scripts through CLI).
  • You can create some sort of placeholder at the root of your directory structure, and work your way up until you find it, then consider this the root and make your include statements relative to this. This will be more portable and work in CLI mode, but it will be slightly more resource intensive.
  • You can use different include statements depending on where you're script including the include file is located, such as include( "includes/header.php" ); if the file you're including is in the includes directory of the directory you're currently in, or include( "../includes/header.php" ); if the includes directory is in the parent directory of the script being run.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top