php - 如何获取 Phar 中的当前工作目录?

标签 php console filesystems command-line-interface phar

当从控制台调用时,如何在 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 包的构建器脚本
(从 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()

关于php - 如何获取 Phar 中的当前工作目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35487003/

相关文章:

PHP Array - 将数组值转换为键

php - Laravel 邮件 : pass string instead of view

c++ - C/C++ : is it possible to pass binary data through the console?

c# - 如何使用 C# 有效地合并巨大的文件

ios - 提取的 iPhone 操作系统图像显示为 0x0

php - 反馈系统只允许每个用户 1 个

php - 登录后 session 未保存

Python 控制台应用程序 - 在输入行上方输出

c# - 从 .BAT 运行带有 .application 文件类型的 c# 控制台应用程序

c# - Powershell - 全局注册 IO.FileSystemWatcher