php get root directory code example
Example 1: php get file location
include __DIR__ . DIRECTORY_SEPARATOR . 'include.php';
echoScriptPath();
function echoScriptPath() {
list($scriptPath) = get_included_files();
echo 'The script being executed is ' . $scriptPath;
}
Example 2: php root path
$_SERVER['DOCUMENT_ROOT']
Example 3: root directory in php
function getHtmlRootFolder(string $root = '/var/www/') {
$ret = str_replace(' ', '', $_SERVER['DOCUMENT_ROOT']);
$ret = rtrim($ret, '/') . '/';
if (!preg_match("#".$root."#", $ret)) {
$root = rtrim($root, '/') . '/';
$root_arr = explode("/", $root);
$pwd_arr = explode("/", getcwd());
$ret = $root . $pwd_arr[count($root_arr) - 1];
}
return (preg_match("#".$root."#", $ret)) ? rtrim($ret, '/') . '/' : null;
}