【问题标题】:How to get current working directory inside Phar?如何在 Phar 中获取当前工作目录?
【发布时间】:2016-05-30 22:42:03
【问题描述】:

从控制台调用时,我如何在 Phar 存档中的 PHP 脚本中 getcwd()

考虑这个调用:

/path/to/my/actual/cwd> php index.php

在这种情况下,getcwd() 将返回 /path/to/my/actual/cwd。现在我们采用相同的脚本,将其放入 Phar 中并像这样调用它:

/path/to/my/actual/cwd> php /path/to/my/phar/archive.phar

这一次,getcwd() 将返回 /path/to/my/phar,因为那是 Phar 存档的当前工作目录,但我没有从该目录调用存档,控制台的 cwd 不同。

我怎样才能得到它?

或者更好的是,如何强制 Phar 中的所有脚本认为它们的 cwd 是控制台?

【问题讨论】:

  • 您能否提供显示问题的示例代码(演示代码 + 它的 phar 生成)?我不认为 getcwd 会被 phar 功能改变。

标签: php console filesystems command-line-interface phar


【解决方案1】:

这个问题很老了,不过我会试着回答一下……

假设我们有以下 Phar 包的构建器脚本
(通过 CLI 调用 php -dphar.readonly=0 build.php):

<?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();

目录结构如下:

app
├── other
└── phar
    ├── build.php
    └── bundle.phar

在目录 /app/other 中调用 Phar 包实际上会在 PHP 7.4 中显示以下内容:

cd /app/other
php /app/phar/bundle.phar

array(2) {
  ["cwd"]=>
  string(31) "/app/other"
  ["dir"]=>
  string(30) "/app/phar"
}

因此,Phar stub 是处理(或保留)上下文的地方,例如 getcwd()

【讨论】:

    猜你喜欢
    • 2011-06-19
    • 2021-01-18
    • 2015-09-02
    相关资源
    最近更新 更多