Question

This might be a little silly question. Lets say I have a directory like this:

./index.php

./browse/blog.php
./browse/articles.php
./browse/categories.php

./includes/header.php
./includes/footer.php

./classes/init.php
./classes/core.php

./user/login.php
./user/register.php

My init.php and core.php need to be included in all my files e.g index.php and blog.php, articles.php and categories.php.

If I include core.php and init.php in header.php it works fine in index.php. But it doesnt work in articles.php, blog.php and so on basically anything that is in folders (browse or user)

header.php contains include_once('../classes/core.php'); and include_once('../classes/init.php');

So my question is how would I be able to include a file in another file which is included in another file.

Let me rephrase. I want core.php and init.php to be included in header.php which is included in all other files. Like index.php and other files that are in folders.

Can I achieve this using relative file paths?

Was it helpful?

Solution

You could use relative paths, but you'd be much better off prepending $_SERVER['DOCUMENT_ROOT'] to your file names to keep things simple.

Update regarding your comment:

$_SERVER['DOCUMENT_ROOT'] provides you with the webroot path in a variable.

$doc_root = $_SERVER['DOCUMENT_ROOT'];
include $doc_root . '/includes/whatever.php';

It will always provide an absolute path, regardless of which directory the calling script is in. It just makes life easy and means you don't have to figure out how many dots and slashes you need to get back to the file you want to include.

OTHER TIPS

header.php

include("../classes/init.php");
include("../classes/core.php");

login.php

include("../includes/header.php");

..and so on..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top