是否可以执行以下操作?
register_shutdown_function('my_shutdown');
function my_shutdown ()
{
file_put_contents('test.txt', 'hello', FILE_APPEND);
error_log('hello', 3, 'test.txt');
}
Run Code Online (Sandbox Code Playgroud)
似乎没有用.顺便说一下,我在PHP 5.3.5上.
Whi*_*ity 22
这取决于您使用的SAPI.register_shutdown_function()的文档页面指出,在某些服务器(如Apache)下,脚本的工作目录会发生变化.
该文件被写入,但不是您的.php文件所在的位置(DocumentRoot),而是在Apache服务器的文件夹(ServerRoot)中.
为防止这种情况,您需要某种hotwire工作文件夹更改.就在你的脚本开始执行时(在前几行),你需要以某种方式存储真正的工作文件夹.创建常量define()是完美的.
define('WORKING_DIRECTORY', getcwd());
Run Code Online (Sandbox Code Playgroud)
你需要像这样修改关闭功能部分:
function my_shutdown ()
{
chdir(WORKING_DIRECTORY);
file_put_contents('test.txt', 'hello', FILE_APPEND);
error_log('hello', 3, 'test.txt');
}
register_shutdown_function('my_shutdown');
Run Code Online (Sandbox Code Playgroud)
这样,当调用函数时,工作文件夹将立即变回真实文件夹,test.txt文件将出现在DocumentRoot文件夹中.
一些修改:最好在声明函数register_shutdown_function() 后调用.这就是为什么我把它写在功能代码下面,而不是它上面.