The real URI of a PHP file?
Is there anyway to get the current URI of a file in PHP, regardless of which file it is being included?
for example:
a.php
is included in b.php
But I want to开发者_Go百科 get the URI of the directory in which a.php
is located in.
There is no "real" URL for a file, as that would imply a 1:1 mapping between URLs and files. Virtual Directories allow for a file to have many different names.
However, if you just want the file system path of a.php
, then try __DIR__
.
Current URI can normally be composed from $_SERVER['HTTPS']
, $_SERVER['SERVER_NAME']
and $_SERVER['REQUEST_URI']
(except the hash identifier, #foo
, which is not even sent to the server).
You can find further reference here but it's normally easier to print_r() the $_SERVER
array.
Clarification: a file can have one URL, many or none at all. There isn't necessarily a 1 to 1 mapping between files and URLs.
If we have this file layout:
/home/foo/htdocs/foo.php
<?php include('./lib/utils.php'); blah();
/home/foo/htdocs/lib/utils.php
<?php function blah(){ }
... where /home/foo/htdocs
is the document root, the way to to obtain the URL of the directory where utils.php
lies is to read __FILE__
from within utils.php
and replace leading $_SERVER['DOCUMENT_ROOT']
with the site's protocol and path. E.g.:
<?php
if( isset($_SERVER['DOCUMENT_ROOT']) ){
$directory = realpath(dirname(__FILE__));
$document_root = realpath($_SERVER['DOCUMENT_ROOT']);
$base_url = ( isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ? 'https' : 'http' ) . '://' .
$_SERVER['SERVER_NAME'];
if( strpos($directory, $document_root)===0 ){
echo $base_url . str_replace(DIRECTORY_SEPARATOR, '/', substr($directory, strlen($document_root)));
}
}
This code may need some tweaking (not all web servers create the same variables) and of course there's no guarantee that the directory's URL will be reachable or useful.
Nota: an earlier version of this answer mentioned $_SERVER['HTTP_HOST']
. While it's fine most of the time, it won't include the port number when a non-default port is being used. $_SERVER['SERVER_NAME']
does.
You can use realpath(__FILE__)
to get the directory in the filesystem. You should be able to translate that to the URI.
realpath()
Using Johan's answer in the comment section, we have:
This answer is highly dependent on your directory structure, make sure you explode by the last folder that leads to your www root! This could be either 'htdocs' or 'public_html' depending on your host.
$my_domain = $_SERVER['HTTP_HOST'];
$this_uri_dir = explode('public_html', dirname(__FILE__)); //this assumes you don't have multiple folders named 'public_html'
echo 'http://'.$my_domain.$this_uri_dir[1].'/';
精彩评论