0plus1
0plus1

Reputation: 4555

php includes is there any way to include a file relative only to that document?

If I have an index.php file that includes inc/footer.php I would write:

include 'inc/footer.php';

If I want to include another file inside footer.php, I must do it relative to the index.php file (the one that is including it). This may not be a problem, but what about if I want to include index.php from an entire different location?

I understand that there are several methods to achieve this like defining an absolute path or using dirname(__FILE__).

This is something that has never been a real problem since one way or another I always figured it out but that I always wondered how exactly includes work in php.

Can someone explain me exaclty what is going on under the hood?

Upvotes: 18

Views: 17501

Answers (2)

Tom Haigh
Tom Haigh

Reputation: 57835

This may help: (from http://php.net/manual/en/function.include.php)

Files for including are first looked for in each include_path entry relative to the current working directory, and then in the directory of current script. E.g. if your include_path is libraries, current working directory is /www/, you included include/a.php and there is include "b.php" in that file, b.php is first looked in /www/libraries/ and then in /www/include/. If filename begins with ./ or ../, it is looked for only in the current working directory or parent of the current working directory, respectively

Your question states:

If I want to include another file inside footer.php, I must do it relative to the index.php file (the one that is including it).

This is true only if the filepath you are trying to include() starts with ./ or ../ . If you need to include a file above the current file using a relative path, you can (as you suggested) use:

include dirname(__FILE__) . '/../file.php';

If you define an absolute path, you can also add this to the current include_path:

set_include_path(get_include_path() . PATH_SEPARATOR . '/absolute/path');

You can then do all your includes relative to '/absolute/path/'.

Upvotes: 40

Derek Organ
Derek Organ

Reputation: 8483

The best place to find the answer is in the PHP manual.

http://php.net/manual/en/function.include.php

Short answer: the path is relative to the executing PHP script no the sub includes.

Setting a global absolute path to your functions, classes etc folders is the best method.

Upvotes: -4

Related Questions