How can I getcwd()
in a PHP script in a Phar archive when called from the console?
Consider this call:
/path/to/my/actual/cwd> php index.php
In this case, getcwd()
will return /path/to/my/actual/cwd
. Now we take the same script, put it in a Phar and call it like this:
/path/to/my/actual/cwd> php /path/to/my/phar/archive.phar
This time, getcwd()
will return /path/to/my/phar
as that is the current working directory of the Phar archive, but I did not call the archive from that directory, the console's cwd is different.
How can I get that?
Or even better, how can I force all scripts in the Phar to think their cwd is the console one?
This question is old, however I'll try to answer it...
Let's assume we have the following builder script for the Phar bundle
(called with php -dphar.readonly=0 build.php
from CLI):
<?php
$phar = new Phar('bundle.phar');
$phar->startBuffering();
$phar->addFile('index.php');
$phar->setStub('<?php var_dump(["cwd" => getcwd(), "dir" => __DIR__]);
__HALT_COMPILER();');
$phar->stopBuffering();
The directory structure looks like the following:
app
├── other
└── phar
├── build.php
└── bundle.phar
Being in directory /app/other
and calling the Phar bundle actually shows the following with PHP 7.4:
cd /app/other
php /app/phar/bundle.phar
array(2) {
["cwd"]=>
string(31) "/app/other"
["dir"]=>
string(30) "/app/phar"
}
Thus, the Phar stub is the place to handle (or preserve) context like getcwd()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With