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 get the URI of the directory in which a.php is located in.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
$_SERVERarray.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/home/foo/htdocs/lib/utils.php… where
/home/foo/htdocsis the document root, the way to to obtain the URL of the directory whereutils.phplies is to read__FILE__from withinutils.phpand replace leading$_SERVER['DOCUMENT_ROOT']with the site’s protocol and path. E.g.: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.