Lan*_*Lan 7 php require include file-exists phar
我的Phar脚本使用fwrite创建一个新文件,该文件工作正常,它在phar之外创建新文件,与phar文件位于同一目录中.
但是当我使用if(file_exists('file.php'))时它不会捡起它.
但是然后包括并要求捡起它.
有谁知道这个问题?经过一段时间的测试和研究似乎无法找到解决方案.
在PHAR的存根中,您可以使用__DIR__魔术常量来获取PHAR文件的文件夹.
考虑到这一点,您可以简单地使用
is_file(__DIR__ . DIRECTORY_SEPARATOR . $path);
Run Code Online (Sandbox Code Playgroud)
检查文件是否存在于PHAR之外.
你只能从存根中执行此操作,并且只有它是自定义存根,而不是由Phar :: setDefaultStub()生成的存根.如果你需要在线下检查文件,你必须以某种方式使该常量值可用,如全局变量,自定义非魔法常量或静态属性或其他文件然后参考的东西.
编辑:实际上,您还可以使用dirname(Phar::running(false))从PHAR中的任何位置获取PHAR的文件夹.如果您不在PHAR中,该函数将返回一个空字符串,因此无论您的应用程序是作为PHAR执行还是直接执行,它都应该正常工作,例如
$pharFile = Phar::running(false);
is_file(('' === $pharFile ? '' : dirname($pharFile) . DIRECTORY_SEPARATOR) . $path)
Run Code Online (Sandbox Code Playgroud)
在 PHP 中处理文件路径和 Phar 档案可能很棘手。Phar 文件中的 PHP 代码会将相对路径视为相对于 Phar 存档,而不是相对于当前工作目录。这是一个简短的例子:
假设您有以下文件:
phar/index.php
test.php
my.phar
Run Code Online (Sandbox Code Playgroud)
index.php 文件位于 phar 目录内。它是 phar 存档的引导程序文件:
function does_it_exist($file){
return file_exists($file) ? "true" : "false";
}
Run Code Online (Sandbox Code Playgroud)
当 PHP 脚本中包含 phar 文件时,将执行引导文件。我们的引导文件只会导致函数“does_it_exist”被声明。
让我们尝试在 test.php 中运行不同的代码,看看每次运行的结果是什么:
//Run 1:
require_once 'phar/index.php'; //PHP file
$file = __DIR__ . "/index.php"; //absolute path
echo does_it_exist($file); //prints "false"
//Run 2:
require_once 'phar/index.php'; //PHP file
$file = "index.php"; //relative path
echo does_it_exist($file); //prints "false"
//Run 3:
require_once 'my.phar'; //phar file
$file = __DIR__ . "/index.php"; //absolute path
echo does_it_exist($file); //prints "false"
//Run 4:
require_once 'my.phar'; //phar file
$file = "index.php"; //relative path
echo does_it_exist($file); //prints "true"
Run Code Online (Sandbox Code Playgroud)
查看运行 4。此代码包含 phar 文件并向函数传递一个相对路径。相对于当前工作目录,index.php 不存在。但相对于 phar 档案的内容,它确实存在,这就是为什么它打印“true”!
小智 5
我今天遇到同样的问题。经过几个小时的挖掘……我找到了答案。
您可以先尝试以下脚本吗?
if(file_exists(realpath('file.php')));
Run Code Online (Sandbox Code Playgroud)
如果文件存在,则问题是
如果仅使用文件名而不包含路径信息,则php对待文件与phar存根有关。例如:
phar:///a/b/c/file.php
因此,您必须使用绝对路径来操作文件,例如:
/home/www/d/e/f/file.php
希望能有所帮助。
标记
| 归档时间: |
|
| 查看次数: |
3449 次 |
| 最近记录: |