Php 关闭处理程序和相对路径

Php 关闭处理程序和相对路径,php,apache,relative-path,Php,Apache,Relative Path,创建一个PHP项目,该项目由两个文件组成—index.PHP,其中包含下面的代码和另一个名为example.png的文件(位于同一目录中) echo file_exists('example.png') ? 'outside the handler - exists' : 'outside the handler - does not exist'; register_shutdown_function('handle_shutdown'); function handle_

创建一个PHP项目,该项目由两个文件组成—
index.PHP
,其中包含下面的代码和另一个名为
example.png
的文件(位于同一目录中)

echo file_exists('example.png')
    ? 'outside the handler - exists'
    : 'outside the handler - does not exist';

register_shutdown_function('handle_shutdown');

function handle_shutdown()
{
    echo file_exists('example.png')
        ? 'inside the handler - exists'
        : 'inside the handler - does not exist';
}

foo();
运行
index.php

以下是您将获得的信息:

outside the handler - exists
Fatal error: Call to undefined function foo() in /path/to/project/index.php on line 16
inside the handler - does not exist
这是我的问题


为什么内部
文件\u不存在
(处理程序中的文件)找不到该文件?

在PHP的某些SAPI上,在关闭函数中,工作目录可以更改。请参见手册页上的此注释:

脚本的工作目录可以在某些web服务器(例如Apache)下的关机功能中更改

相对路径依赖于工作目录。更改后,将再也找不到该文件

如果改用绝对路径,则不会遇到该问题:

$file = __DIR__ . '/' . 'example.png';

echo file_exists($file)
    ? 'outside the handler - exists'
    : 'outside the handler - does not exist';

$handle_shutdown = function() use ($file)
{
    echo file_exists($file)
        ? 'inside the handler - exists'
        : 'inside the handler - does not exist';
}

register_shutdown_function($handle_shutdown);

有关函数,请参阅文档

有一张便条说

Working directory of the script can change inside the shutdown function under some web servers, e.g. Apache.

我不太清楚原因,但PHP文档在
register\u shutdown\u function()
下的注释中警告了这一点,其中指出:

Note:

Working directory of the script can change inside the shutdown function under some web servers, e.g. Apache.

您可以尝试回显
getcwd()
,了解实际发生的情况。

example.php或example.png?这通常不起作用。在PHP的关闭阶段,需要使用绝对路径。请参阅上的注释,这可能是一个输入错误,但从输出中可以看到相同的文件存在。检查在句柄关闭内外返回不同的值function@Rafael,它应该是
example.png
。如果工作目录发生更改,这里有一个指向解决方案的链接。