I have the following problem that I am having a hard time deciphering. I have the files distributed as follows:
/
|___control
| |___usuarios.php
|___vista
|___addUser.php
|___modelo
| |___conexion.php
|___index.php
The following happens, both the "addUser.php" and "index.php" files use the "usuarios.php" file. The file "users.php" has a require_once()
of the file "connection.php".
And since "addUser.php" and "index.php" are in different places in the project, the _path_
one that is added in "usuarios.php" creates conflicts require_once()
.
Any idea how to solve?
Personally, to avoid problems, it's better to use absolute paths. They are better adapted to any implementation, even if the environment is changed (but keeping the same structure).
Since it is not specified in the question, I use as an example an absolute path like this:
/var/www/httpdocs
And the real case you describe, that both addUser.php and index.php use users.php .
At this point we propose three options:
Option 1 - Relative Paths
They are the ones you are using and with the exception of certain cases, they usually cause the problems you are encountering. Throwing the error that it cannot find the requested file.
addUser.php
index.php
Option 2 - Absolute paths with text
Paths always point to the file, regardless of the level from which it is included and as long as the structure is not changed.
This would solve the problem you have, but it has the drawback that if you change to another environment, with an example path like the following
/var/www/midominio
, all the paths of all the files must be changed. It is a tedious thing to maintain.addUser.php
index.php
Option 3 - Absolute paths using predefined constants
Personally I think it is the most recommended and easy to maintain. If you keep 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 that is using it is located. And itdirname()
returns the parent directory, in combinationdirname(__DIR__)
it would return the absolute path of the parent directory where the file that is using it is located.addUser.php
index.php
If you find errors, comment and I'll edit
The easiest thing is that the address of the file you require is complete, for example: for my server
and no: