PHP Phar - file_exists() issue

file-exists, include, phar, php, require

Solution

At the PHAR's stub, you can use the `__DIR__` magic constant to get the PHAR file's folder.

With that in mind, you can simply use

is_file(__DIR__ . DIRECTORY_SEPARATOR . $path);

To check for a file's existence outside the PHAR.

You can ONLY do this from the stub, and ONLY if it's a custom stub, as opposed to one generated by Phar::setDefaultStub(). If you need to check for files further down the line, you'll have to make that constant's value available somehow, like a global variable, a custom non-magical constant or a static property or something, which other files then consult with.

EDIT: Actually, you can also use `dirname(Phar::running(false))` to get the PHAR's folder from anywhere in the PHAR. That function returns an empty string if you're not within a PHAR, so whether your application is executed as a PHAR or directly, it should work fine, e.g.

$pharFile = Phar::running(false);
is_file(('' === $pharFile ? '' : dirname($pharFile) . DIRECTORY_SEPARATOR) . $path)

Problem

My Phar script creates a new file with fwrite, which works fine, it creates the new file outside the phar, in the same directory as the phar file. But then when i use if(file_exists('file.php')) it doesn't pick it up. But then include and require do pick it up. Anyone know about this problem? Been testing and researching for a while a can't seem to find a solution.

Original source