Search code examples
phpcommand-line-interfacephar

how to get a .phar file real directory within the phar file code?


I am trying to create a php executable (a phar file) for generating some files, and I would like to know how to get the real path of the phar file (within the phar file code).

What I want to do is to create a folder in the same level of the phar file and create the new files there, but realpath(__DIR__.'/../') does not seem to work.

Thanks


Solution

  • As shown in https://stackoverflow.com/a/28775172/282601 the __FILE__ constant has the full path with the scheme:

    phar:///home/cweiske/Dev/test/phar/test.phar/path/to/foo.php
    

    __DIR__ is similar:

    phar:///home/cweiske/Dev/test/phar/test.phar/path/to
    

    So when calling realpath(__DIR__) you still have the phar:// prefix that prevents you from loading the file.

    You have to remove the phar:// scheme as well as the path of the file inside the .phar to get the phar location with __DIR__.


    Much easier is Phar::running(false), which simply returns the path:

    /home/cweiske/Dev/test/phar/test.phar