Get absolute path of initially run script

615,589

Solution 1

echo realpath(dirname(__FILE__));

If you place this in an included file, it prints the path to this include. To get the path of the parent script, replace __FILE__ with $_SERVER['PHP_SELF']. But be aware that PHP_SELF is a security risk!

Solution 2

__FILE__ constant will give you absolute path to current file.

Update:

The question was changed to ask how to retrieve the initially executed script instead of the currently running script. The only (??) reliable way to do that is to use the debug_backtrace function.

$stack = debug_backtrace();
$firstFrame = $stack[count($stack) - 1];
$initialFile = $firstFrame['file'];

Solution 3

The correct solution is to use the get_included_files function:

list($scriptPath) = get_included_files();

This will give you the absolute path of the initial script even if:

  • This function is placed inside an included file
  • The current working directory is different from initial script's directory
  • The script is executed with the CLI, as a relative path

Here are two test scripts; the main script and an included file:

# C:\Users\Redacted\Desktop\main.php
include __DIR__ . DIRECTORY_SEPARATOR . 'include.php';
echoScriptPath();

# C:\Users\Redacted\Desktop\include.php
function echoScriptPath() {
    list($scriptPath) = get_included_files();
    echo 'The script being executed is ' . $scriptPath;
}

And the result; notice the current directory:

C:\>php C:\Users\Redacted\Desktop\main.php
The script being executed is C:\Users\Redacted\Desktop\main.php

Solution 4

__DIR__

From the manual:

The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory.
__FILE__ always contains an absolute path with symlinks resolved whereas in older versions (than 4.0.2) it contained relative path under some circumstances.

Note: __DIR__ was added in PHP 5.3.0.

Solution 5

If you want to get current working directory use getcwd()

http://php.net/manual/en/function.getcwd.php

__FILE__ will return path with filename for example on XAMPP C:\xampp\htdocs\index.php instead of C:\xampp\htdocs\

Share:
615,589

Related videos on Youtube

inquam
Author by

inquam

Very social, easy going, fun loving person with an apetite for new challanges and new knowledge who has been there and done that. Thats a good way to sum it all up. Have a huge foundation of experience, from different technologies, platforms, enviroments, companies, methodologies, wishes and wants. Desktop apps, server apps, web apps, games etc, both front-end and back-end. But also someone who knows that there's always more to learn and someone who knows things better than you ;)

Updated on May 29, 2020

Comments

  • inquam
    inquam almost 4 years

    I have searched high and low and get a lot of different solutions and variables containing info to get the absolute path. But they seem to work under some conditions and not under others. Is there one silver bullet way to get the absolute path of the executed script in PHP? For me, the script will run from the command line, but, a solution should function just as well if run within Apache etc.

    Clarification: The initially executed script, not necessarily the file where the solution is coded.

    • inquam
      inquam over 9 years
      true indeed mathheadinclouds. I accepted it a long time ago when I had only one script and it worked for me. I removed the accepted answer to make it clear it does not solve the initial problem. Storing the FILE constant when the execution starts in a script is one way to go, but far from ideal.
    • Bitterblue
      Bitterblue over 4 years
      requested script is what you wanted, current script = with this solution code
  • inquam
    inquam over 13 years
    This was exactly what I wanted
  • Your Common Sense
    Your Common Sense over 13 years
    what's the use of realpath here?
  • user3167101
    user3167101 over 13 years
    What is the security risk of using $_SERVER['PHP_SELF'] ? Because people echo it and it contains the URL which may be malicious?
  • rik
    rik over 13 years
    @Col. Shrapnel: "Since PHP 4.0.2, __FILE__ always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances." plus "dirname() operates naively on the input string, and is not aware of the actual filesystem, or path components such as '..'.
  • zerkms
    zerkms over 13 years
    @rik: also, what security issue can cause PHP_SELF ??
  • Your Common Sense
    Your Common Sense over 13 years
    @zerkms it can't be. 5.0.2 probably. 4.0.2 is < 4.1 and 4.1 itself is as ancient, as dino's petrified shit
  • zerkms
    zerkms over 13 years
    @Col. Shrapnel: yep, it is 1999. I thought I can rely on dates at museum.php.net.
  • CMCDragonkai
    CMCDragonkai over 10 years
    If I'm using a front controller pattern. Would __FILE__ return the index.php's location or the included file's location? How would I get the index.php's location?
  • CMCDragonkai
    CMCDragonkai over 10 years
    Well __FILE__ does point to the current script's path. But I haven't found anything to shows the current index.php's path.
  • zerkms
    zerkms over 10 years
    @CMCDragonkai: ask a separate question then
  • Mark Richards
    Mark Richards almost 10 years
    CAUTION: if the script is in an apache2 virtual directory, the information returned does NOT provide the real path location on the physical server. I wanted this for debug purposes, and even the $_SERVER variables do not provide this. For example, if index.php exists in /var/www/vpath1/html and /var/www/html/ and /var/www/vpath2/html, and each of these is virtually mapped to /var/www/html, then /var/www/html is what you will see, no matter which virtual server is used.
  • zerkms
    zerkms almost 10 years
    @Mark Richards: what __FILE__ returns is a REAL filesystem path. It doesn't care of any virtual servers or whatever else your webserver defines, but just a filesystem path.
  • inquam
    inquam about 9 years
    Yea, but the idea is to be able to get the absolute path to the "firing script" A.php even inside B.php if that is included by A.php. It CAN or course be done by storing the initial script for later access, but the question was if it's possible to get it without doing that.
  • Benubird
    Benubird almost 9 years
    Why do you need realpath? Is dirname not enough on its own?
  • Redips77
    Redips77 over 8 years
    __DIR__ is'nt a good choice? You get the absolute path for the current php file.
  • zerkms
    zerkms over 8 years
    @Redips77 __DIR__ does not return the absolute path to the current file, it returns the absolute path to the directory that hosts the current file.
  • inquam
    inquam over 8 years
    Note that my initial question was to get the initial executed script file (without manually saving it once executed). __FILE__ will get you the current file you are in, not the file of the script/url that might have included the current file returned by __FILE__
  • zerkms
    zerkms over 8 years
    @inquam actually I've put my question BEFORE you have put your note (9:05 vs 9:08). So your initial question that I actually answered did not contain it. I'm sorry I cannot read minds and answer questions to be asked 3 minutes after I answered them.
  • inquam
    inquam over 8 years
    @zerkms: My deepest appologies :)... I still get random plings in my phone related to this question to this date and still none have been able to answer it so happened to write something today. After some research into the code (valid at the time) I actually don't believe it is/was possible. Some combination using the DOCUMENT_ROOT and SCRIPT_NAME variables in the $SERVER array would come close (and with some more info probably solve it). But I seem to remember some of the data in $SERVER being able to be spoofed or not presented in some configurations so I didn't want to rely on that.
  • zerkms
    zerkms over 8 years
    @inquam the only reliable way to get the script that initiated runtime in php is using debug_backtrace. All other answers, including mine, do not answer the current question.
  • inquam
    inquam over 8 years
    @zerkms: Do debug_backtrace still incure a massive performance hit? I know it did in old versions of PHP.
  • zerkms
    zerkms over 8 years
    @inquam well, I'm not sure about its "massiveness", but if you need a reliable solution I don't see any other possibilities. Everything else may return just incorrect results.
  • inquam
    inquam over 8 years
    Sry, the idea is to get the first fired script... Not the one you happen to be in now. So an inclusion tree of a.php->b.php->c.php should be the path of a.php if checked in c.php. The only way that seems to be reliable is to use the debug_backtrace() function.
  • Bronek
    Bronek over 7 years
    When I was checking this solution against different servers it always gave me path with the linux like dir separators regardless of host's OS (Windows and Linux). To me that is an advantage.
  • Meisner
    Meisner about 7 years
    as of PHP>=5.3.0, echo __DIR__ is the equivalent
  • Bram Vanroy
    Bram Vanroy almost 7 years
    As far as I can see PHP_SELF is only a security risk when using it on forms. __DIR__ is not the same as PHP_SELF, by the way.
  • Christoffer Bubach
    Christoffer Bubach over 5 years
    Throwing an exception instead of calling debug_backtrace() will basically give you the same backtrace information a lot quicker.
  • zerkms
    zerkms over 5 years
    @ChristofferBubach you don't even need to throw it: an exception object collects the stack trace during construction.
  • Christoffer Bubach
    Christoffer Bubach over 5 years
    Yes, sorry - that's what I was meaning to write.
  • Paolo
    Paolo over 4 years
    This solution works but it's worth mentioning that, reading the documentation, there is no mention that the initially run script's path is the first item of the array returned by get_included_files(). I suggest to store __FILE__ into a constant at the beginning of the script meant to be initially run.
  • Salman A
    Salman A almost 2 years
    Both options in the answer don't not return (i) absolute path (ii) the "initially run" script