是否可以执行以下操作?
register_shutdown_function('my_shutdown');
function my_shutdown ()
{
file_put_contents('test.txt', 'hello', FILE_APPEND);
error_log('hello', 3, 'test.txt');
}
似乎不起作用。 顺便说一下,我在PHP 5.3.5上。
答案 0 :(得分:21)
这取决于您使用的SAPI。 documentation page for register_shutdown_function()表示在某些服务器(如Apache)下,脚本的工作目录会发生变化。
文件被写入,但不是.php
文件的位置( DocumentRoot ),而是写在Apache服务器的文件夹中( ServerRoot )。< / p>
为了防止这种情况,您需要某种hotwire工作文件夹更改。就在你的脚本开始执行(在前几行)时,你需要以某种方式存储真正的工作文件夹。使用define()
创建常量非常适合。
define('WORKING_DIRECTORY', getcwd());
你需要像这样修改关闭功能部分:
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');
这样,当调用函数时,工作文件夹将立即更改回真实文件夹,test.txt
文件将出现在 DocumentRoot 文件夹中。
一些修改:最好在声明函数后调用register_shutdown_function()
。这就是为什么我把它写在下面功能代码,而不是它上面。
答案 1 :(得分:1)
检查:(来自here)
Note:
Working directory of the script can change inside the shutdown function
under some web servers, e.g. Apache.
使用getcwd();