What I want is to be able to get the host and the sub-folder of a particular site. For example: get http://example:81/test/
from http://example:81/test/pagename.php
.
It should also work with same url http://example:81/test/
and with multiple levels of sub-folders such as http://example:81/test/test2/somepage.php
.
It should not get the structure of the file within a folder itself such as http://example:81/test/images/page.php
should still be http://example:81/test/
and not http://example:81/test/images/
.
I tried using
$_SERVER['HTTP_HOST'] // only provides example:81
$_SERVER['REQUEST_URI'] // provides full path example:81/test/images/
Essentially I want to get is the url of the index.php file even if it is in a sub-folder.
Is there any way to achieve this?
You would probably have to build your own string to get the full url.
<?php
$url = 'http'.(isset($_SERVER['HTTPS'])?'s':'').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
If you want details from that, you can use parse_url()
<?php
$details = parse_url($url);
print_r($details);
would output something like:
Array
(
[scheme] => http
[host] => example.com
[port] => 81
[path] => /test/test2/
[query] => somepage.php
)
Edit:
If you want the path to the file, you can use $_SERVER['PHP_SCRIPT']
to get the filename of the called script relative to the document root or $_SERVER['SCRIPT_FILENAME']
to get the server path including the document root. There are also the built in constants __DIR__
and __FILE__
that have the server path up to the current script, even when included. All of these can be used with dirname() to get the directory of the variable and basename() to get just the filename. There is also $_SERVER['DOCUMENT_ROOT']
that has the path up to the web root.
So to get a path under the same directory this script resides in, if the script /var/www/test/index.php
is called, you can use dirname(__FILE__).'/some/sub/dir/'
.
You can see all the server variables by just doing a print_r of $_SERVER
or even better you can call phpinfo()
to get a nice output of all defined php modules and variables.
i had a similar problem in a project of mine; i wanted to be able to get the subfolder
via a script filename (etc. index.php) I tried some methods but the following (ugly) method worked. The trick is to "feed" the method with all the possible "places" that all .php files can exist.
If the script name
is found into one of these places, then subtract
the part LEFT of those places; this part should be the subfolder
(if there's any).
Yes, its ugly but worked for me...
$string = $_SERVER["SCRIPT_NAME"];
$subfolder = NULL;
// tries to find the 'subfolder' by checking all possible PHP calls
$places = array("/","plugins/","system/php");
foreach($places as $key=>$val) {
$pos = strpos($string,$val);
if ($pos !== FALSE && !isset($subfolder)) {
$subfolder = substr($string,0,$pos-1);
break;
}
}