Personally, to avoid problems, it is better to use absolute routes. They adapt better to any implementation, even if the environment changes (but maintaining the same structure).
Since it is not specified in the question, I give as an example an absolute path like this: /var/www/httpdocs
And the real case that you describe, that both addUser.php and index.php , use users.php .
.
├── index.php
├── control
│ └── usuarios.php
└── vista
└── addUser.php
At this point we propose three options:
We use relative routes
We use absolute paths with text
We use absolute paths using predefined constants
Option 1 - Relative routes
They are the ones you are using and with the exception of certain cases, it usually causes the problems you are encountering. Launching the error that can not find the requested file.
addUser.php
include_once '../control/usuarios.php';
index.php
include_once './control/usuarios.php';
Option 2 - Absolute paths with text
The routes always point to the file, independently from which level it is included and as long as the structure is not changed.
This would solve the problem you have, but it has the disadvantage that if you change to another environment, with an example path like the following /var/www/midominio
all the routes of all the files must be changed. It's kind of tedious to maintain.
addUser.php
include_once '/var/www/httpdocs/control/usuarios.php';
index.php
include_once '/var/www/httpdocs/control/usuarios.php';
Option 3 - Absolute paths using predefined constants
Personally I think it is the most recommended and easy to maintain. If you maintain the structure and change the environment, it probably produces few or no errors.
The constant __DIR__
returns the absolute path of the directory where the file is located. he is using it. And dirname()
returns the parent directory, in combination dirname(__DIR__)
we would return the absolute path of the parent directory where the file that is using it is located.
addUser.php
// /var/www/httpdocs/control/usuarios.php
include_once dirname( __DIR__ ) . '/control/usuarios.php';
// Es equivalente a:
// include_once __DIR__ . '/../control/usuarios.php';
index.php
// /var/www/httpdocs/control/usuarios.php
include_once __DIR__ . '/control/usuarios.php';
As a note, both __DIR__
and dirname()
end the routes without the / bar at the end. So, both to enter the directories /dir/...
, and to leave them /../dir/...
you have to build the route starting with a bar / .
If they find errors, comment and edit