Code

Coding, Programming & Algorithms, Tips, Tweaks & Hacks
Search

Absolute path of current php file in execution

Sometimes it is necessary to know the absolute path of the current php-file in execution. A common example is when you have loaded a 3rd-party module and all its related files (like php, css, js, images etc) are in a folder of its own and moving these related files to your own specific-folders for the sake of organization can be disadvantageous instead of structuring them to match your own. If moving the files to different locations, editing the module code could end up being cumbersome. Hence, modules are like Java packages where all the files are kept in a separate folder and better left untouched. In php, if we can extract a lot of file and folder information from these global variables $_SERVER['DOCUMENT_ROOT'], $_SERVER['SCRIPT_FILENAME'], $_SERVER['SCRIPT_NAME'], $_SERVER['PHP_SELF'] But none of these would give the current php-file name in consideration if mod_rewrite, include() etc were used to retrieve a php file. PHP's __FILE__ magic constant is the only way to retrieve the absolute path. Given this path you can create a OO module within which you can access the related-files within the folder and thus be independent of any CMS. This is one very simple function you'll come across but I still felt the need to emphasize on this function.
PHP
<?php
echo __FILE__AbsolutePath(__FILE__)."\n";

function __FILE__AbsolutePath($Filename)
 {
        switch (PHP_OS)
         {
                case "WINNT": $needle = "\\"; break;
                case "Linux": $needle = "/";  break;
                default:      $needle = "/";  break; // TODO : Mac check
         }
        $AbsPath = substr($Filename, 0, strrpos($Filename, $needle));
        return $AbsPath;
 }
?>
I haven't done a MAC and other OS checks. If you have tried this on an OS that shows a different value for PHP_OS, please do share it with others.

Update: Getting the current file equivalent to __FILE__ can be retrieved using the debug_backtrace() function.
PHP
<?php
function __FILE__AbsolutePath()
 {
        $d = debug_backtrace();
        $Filename = $d[0]['file'];

        switch (PHP_OS)
         {
                case "WINNT": $needle = "\\"; break;
                case "Linux": $needle = "/";  break;
                default:      $needle = "/";  break; // TODO : Mac check
         }
        $AbsPath = substr($Filename, 0, strrpos($Filename, $needle));
        return $AbsPath;
 }
?>
Vanakkam !

0 comments: