I have file /root/update/test.php. There's also a file, /root/connect.php; This file has a line
include "../config.php";
In /root/update/test.php. There's the code
set_include_path(".:/root"); include "connect.php";
When I run /root/update/test.php, it finds connect.php, but fails to find config.php, giving me
PHP Warning: include(../config.php): failed to open stream: No such file or directory in /root/connect.php on line 2 PHP Warning: include(): Failed opening '../config.php' for inclusion (include_path='.:/root')
This is confusing to me because the warnings make it seem like I'm doing everything correctly - the include path is /root, and it's looking for file ../config.php (/config.php), which exists. Can someone clear this up for me? Note that using absolute paths is not an option for me, due to deploying to a production server that I have no access to.
Ubuntu/Apache
A relative path refers to a location that is relative to a current directory. Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory.
The include (or require ) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement. Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website.
The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.
You could always include it using __DIR__
:
include(dirname(__DIR__).'/config.php');
__DIR__
is a 'magical constant' and returns the directory of the current file without the trailing slash. It's actually an absolute path, you just have to concatenate the file name to __DIR__
. In this case, as we need to ascend a directory we use PHP's dirname
which ascends the file tree, and from here we can access config.php
.
You could set the root path in this method too:
define('ROOT_PATH', dirname(__DIR__) . '/');
in test.php would set your root to be at the /root/
level.
include(ROOT_PATH.'config.php');
Should then work to include the config file from where you want.
While I appreciate you believe absolute paths is not an option, it is a better option than relative paths and updating the PHP include path.
Use absolute paths with an constant you can set based on environment.
if (is_production()) { define('ROOT_PATH', '/some/production/path'); } else { define('ROOT_PATH', '/root'); } include ROOT_PATH . '/connect.php';
As commented, ROOT_PATH
could also be derived from the current path, $_SERVER['DOCUMENT_ROOT']
, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With