Reputation: 347
I want to determine if the PHP file I am on install.php
is in a subdomain/subdirectory (basically not at domain.com/install.php).
see below
Upvotes: 7
Views: 5009
Reputation: 799
My answer is not 100% complete because it hasn't been tested on all server environments, but I can confirm this will work if using the embedded PHP web engin or using an apache server with a symlinked web folder. The function returns the subfolder in the form /folder because that is what I needed. If someone can check Nginx it will help a lot. Notice the use of CONTEXT_DOCUMENT_ROOT vs DOCUMENT_ROOT && SCRIPT_NAME vs REQUEST_URI because that could mean a router URL vs actual live file. To use as per the asked question you could say
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;
}
Upvotes: 0
Reputation: 11
if ($handle = opendir('directory/subdirectory/')) {
while (false !== ($entry = readdir($handle))) {
if (strpos($entry, '.php') !== false) {
echo $entry."<br>";
}
}
closedir($handle);
}
Upvotes: 0
Reputation: 69937
Your syntax error is because you are missing the ;
at the end of $scriptname="install.php"
.
Your method looks like it should work okay.
Another way you could determine if the file is installed at the domain root instead of a folder or subdomain would be something like this:
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
}
}
Upvotes: 3
Reputation: 780909
Use dirname($_SERVER['SCRIPT_NAME'])
to get the directory portion of the URI.
Upvotes: 6
Reputation: 5104
To scan specific directories:
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
}
To scan all 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
}
}
}
Upvotes: 0
Reputation: 7739
Instead of using $_SERVER['SCRIPT_NAME']
use $_SERVER['REQUEST_URI']
See PHP $_SERVER Documentation
Upvotes: 0