Search code examples
phpajaxincludeinclude-pathserver-side-includes

Including Files from Different Directories


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)?


Solution

  • 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");