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

假如想象 提交于 2019-12-10 13:06:50

问题


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


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/27838025/how-to-get-a-phar-file-real-directory-within-the-phar-file-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!