stack stack - 6 months ago 9
PHP Question

How to include a script from nested folders?

I have this folder-structure:

-out
-DBconnection.php
-root
-application
-contact.php


Also here is the content of
contact.php
:

function index(){
<form action="http://example.com/localhost/application/contact/check">
// some code here ...
</form>
}

function check(){
// I need to include DBconnection.php script here
require_once( /* what path */ );
...
}


But this path doesn't work:
../../out/DBconnection.php
.

Note: path above works into
index()
function as well. However
index()
is defined as default in my routing system and when I open this path

http://example.com/contact
/* which is the same as
http://example.com/contact/index
*/


Then
index
will be executed. So how can I include
DBconnection.php
into
check()
function?

Answer

What I do in cases like this is to add at the very top of the root file the following lines:

define( 'DS',       DIRECTORY_SEPARATOR );
define( 'ROOT',     dirname(dirname(dirname(__FILE__))) ); // Root is ../../

And when I include a file, I use those constants to get the path (which is always relative to the rood document):

require ROOT . DS . "out" . DS . "DBconnection.php";
Comments