Including Files from Different Directories

394 views Asked by At

So I have these files:

/
|
+ include/
|   |
|   + database.php
|
+ cart/
|   |
|   + table.php
|
+ cart.php

My cart.php displays the page with a table that was generated by table.php (included file). The reason that I have a separated file for the table is because I have to generate the table again after some operations in cart.php — the current table is removed and a new one is loaded with Ajax. However, my table.php file has this line:

require_once("include/database.php");

This is quite problematic, since when the file is included from cart.php, the path makes sense. But when it's called by itself, the current directory will be cart/ and there is no include directory in cart/.

Is there any way to fix this problem? I'd like to avoid using the big absolute path. Is it possible to tell PHP that include/ should be always searched for files, no matter where it was called? It it is, where should I do that (in which file)?

3

There are 3 answers

0
Zul On BEST ANSWER

If you are using .htaccess, you can set include path :

.htaccess:

php_value include_path "/path/to/include/"

php file:

require_once get_include_path().'file.php';


Another way :

require_once($_SERVER['DOCUMENT_ROOT']."/include/database.php");
1
MetalFrog On

In table.php

require_once('../include/database.php');

Well, rereading your question, it looks like you want to autoload things, but we don't have enough information to determine if your classes are set up in a way conducive to autoloading.

1
Oldskool On

In this case I would suggest defining the (absolute) root path of your application in a constant, for example, add this to your config/bootstrap:

// Absolute path to your application's root directory
define('APP_ROOT', '/var/www/vhosts/example.com/httpdocs');

Then you can just include using that constant, like:

require_once(APP_ROOT . '/include/database.php');