8

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

itsjavi
  • 2,467
  • 1
  • 19
  • 24

2 Answers2

8

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
Community
  • 1
  • 1
cweiske
  • 27,869
  • 13
  • 115
  • 180
  • That only gets the path of CURRENT file, not the relative or other file. – Tomas Votruba Jul 21 '20 at 20:33
  • Behaviour of `Phar::running` and `__FILE__` changes within the context of the PHAR stub. In those cases, `Phar::running(true/false)` will always return `''`, and `__FILE__` will return the PHAR path _without_ `phar://` at the beginning. This is mentioned briefly on https://www.php.net/manual/en/phar.running.php : "Inside the stub of an archive, Phar::running() returns "". Simply use \_\_FILE\_\_ to access the current running phar inside a stub. " – AlbinoDrought Sep 24 '20 at 15:59
1

the answer is

 $string = 'phar://E:/php/www/my.phar';
 $string = pathinfo($string);
 $_dir_ = parse_url($string['dirname']);
 echo $_dir_['host'].':/'.$_dir_['path'];

result

E:/php/www

Ganesh Kandu
  • 561
  • 4
  • 12