我想确定我所在的 PHP 文件install.php
是否在子域/子目录中(基本上不在 domain.com/install.php 中)。
找到解决我的问题的方法
见下文
用于dirname($_SERVER['SCRIPT_NAME'])
获取 URI 的目录部分。
您的语法错误是因为您;
缺少$scriptname="install.php"
.
您的方法看起来应该可以正常工作。
您可以确定文件是否安装在域根目录而不是文件夹或子域的另一种方法是这样的:
function subdomboolcheck()
{
$root = $_SERVER['DOCUMENT_ROOT'];
$filePath = dirname(__FILE__);
if ($root == $filePath) {
return false; // installed in the root
} else {
return true; // installed in a subfolder or subdomain
}
}
要扫描特定目录:
if(file_exists('/subdir/install.php')) {
// it exists there
} elseif(file_exists('/subdir2/install.php')) {
// it exists there
} else {
// it's not in these directories
}
扫描所有目录:
$files = glob('/*');
foreach($files as $file) {
//check to see if the file is a folder/directory
if(is_dir($file)) {
if(file_exists($file . 'install.php')) {
// it was found
} else {
// it was not found
}
}
}
而不是使用$_SERVER['SCRIPT_NAME']
使用$_SERVER['REQUEST_URI']
if ($handle = opendir('directory/subdirectory/')) {
while (false !== ($entry = readdir($handle))) {
if (strpos($entry, '.php') !== false) {
echo $entry."<br>";
}
}
closedir($handle);
}
我的答案不是 100% 完整,因为它尚未在所有服务器环境上进行测试,但我可以确认,如果使用嵌入式 PHP Web 引擎或使用带有符号链接 Web 文件夹的 apache 服务器,这将起作用。该函数以 /folder 的形式返回子文件夹,因为这是我需要的。如果有人可以检查 Nginx,它将有很大帮助。请注意使用 CONTEXT_DOCUMENT_ROOT vs DOCUMENT_ROOT && SCRIPT_NAME vs REQUEST_URI 因为这可能意味着路由器 URL 与实际实时文件。要按照提出的问题使用,您可以说
If (!empty(getSubFolder())) {
//Do some stuff here
}
/**
* Logic to determine the subfolder - result must be /folder
*/
function getSubFolder() {
//Evaluate DOCUMENT_ROOT && CONTEXT_DOCUMENT_ROOT
$documentRoot = "";
if (isset($_SERVER["CONTEXT_DOCUMENT_ROOT"])) {
$documentRoot = $_SERVER["CONTEXT_DOCUMENT_ROOT"];
} else
if (isset($_SERVER["DOCUMENT_ROOT"])) {
$documentRoot = $_SERVER["DOCUMENT_ROOT"];
}
$scriptName = $_SERVER["SCRIPT_FILENAME"];
//echo str_replace($documentRoot, "", $scriptName);
$subFolder = dirname( str_replace($documentRoot, "", $scriptName));
if ($subFolder === "/" || (str_replace($documentRoot, "", $scriptName) === $_SERVER["SCRIPT_NAME"] && $_SERVER["SCRIPT_NAME"] === $_SERVER["REQUEST_URI"])) {
$subFolder = null;
}
return $subFolder;
}