问题
I am playing with output buffering in my script and stumbled upon unexpected behaviour.
Writing to a file works everywhere else in my script, but it doesn't quite do so after entering the register_shutdown_function()-function.
I get a warning telling me I don't have permission to write to the file. So I checked which path I was in. Apparently the current working directory vanishes from the moment you enter the shutdown function.
My question is not particularly on how to solve this; As you can see, I just included the correct path. My question is, is this expected behavior and if so, what's the logic behind it?
I'm on OSX/MAMP-PRO if that matters. Haven't tried it yet on another box.
<?
register_shutdown_function('_lib_bootstrap_end');
ob_start();
_lib_bootstrap_start();
file_put_contents('test1.log','this_one_writes_fine');
function _lib_bootstrap_start()
{
echo getcwd()."\n"; // prints '/Users/macbook/Documents/WWW';
file_put_contents('test2.log','this_one_writes_fine');
}
function _lib_bootstrap_end()
{
global $html;
file_put_contents('test3.log', 'this_one_triggers_warning');
$html[] = ob_get_contents();
$return = implode("\n",$html);
ob_end_clean();
echo $return;
echo getcwd()."\n"; // prints '/';
file_put_contents('test4.log', 'this_one_triggers_warning');
// prints 'Warning: file_put_contents(test4.log): failed to open stream: Permission denied in ob_problem.php on line 24'
file_put_contents($_SERVER['DOCUMENT_ROOT'].'/'.'test5.log','this_one_writes_fine');
}
?>
回答1:
The behaviour is expected according to the manual page for register_shutdown_function():
Working directory of the script can change inside the shutdown function under some web servers, e.g. Apache.
I don't know the reasoning behind this.
来源:https://stackoverflow.com/questions/36384308/php-file-put-contents-doesnt-work-as-expected-within-in-register-shutdown-funct