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
This question is related to
php
function relativepath($to){
$a=explode("/",$_SERVER["PHP_SELF"] );
$index= array_search("$to",$a);
$str="";
for ($i = 0; $i < count($a)-$index-2; $i++) {
$str.= "../";
}
return $str;
}
Here is the best solution i made about that, you just need to specify at which level you want to stop, but the problem is that you have to use this folder name one time.
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.
Source: Stackoverflow.com