Create a PHP project that consist of 2 files - index.php
that contains the code below and another file (in the same directory) called 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();
Run index.php
.
Here's what you'll get:
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
Here's my question.
Why can't the inside file_exists
(the one in the handler) find the file?
I am not exactly sure why the reason, but the PHP documentation does warn of this in the note under register_shutdown_function()
which states:
Note:
Working directory of the script can change inside the shutdown function under some web servers, e.g. Apache.
You might try echoing out getcwd()
to get an idea as to what is actually happening.
On some SAPIs of PHP, in the shutdown function the working directory can change. See this note on the manual page of the register_shutdown_function
:
Working directory of the script can change inside the shutdown function under some web servers, e.g. Apache.
A relative path is dependent on the working directory. With it changed, the file is not found any longer.
If you use an absolute path instead, you do not run into that problem:
$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);
See the documentation for the function,
http://php.net/manual/en/function.register-shutdown-function.php
There is a note stating,
Working directory of the script can change inside the shutdown function under some web servers, e.g. Apache.