在请求结束前调用特定函数

时间:2014-04-03 14:28:07

标签: php

我有一个PHP应用程序,并希望在请求结束时调用特定函数(此函数将信息写入日志文件)。实际上,我希望这个函数最后被调用,无论代码采用什么路由,无论以前调用什么函数。

有没有办法知道或找出PHP何时准备好将信息发送回网络服务器?

function req_end() {
    global $logger;
    $logger->log("----------------------------------------------", PEAR_LOG_INFO);
    $logger->log("                 Request End                  ", PEAR_LOG_INFO);
    $logger->log("==============================================", PEAR_LOG_INFO);
    $logger->log("", PEAR_LOG_INFO);
}
register_shutdown_function('req_end');

如果我在index.php文件的末尾调用req_end,那么它会写入日志,如果没有,则根本不会调用它。 谢谢 Crouz

2 个答案:

答案 0 :(得分:0)

我认为你正在寻找这个register_shutdown_function()

只要脚本完成,它就会运行一个函数,即使它是exit()

这是从文档中复制的示例:

<?php
function shutdown()
{
    // This is our shutdown function, in 
    // here we can do any last operations
    // before the script is complete.

    echo 'Script executed with success', PHP_EOL;
}

register_shutdown_function('shutdown');
?>

答案 1 :(得分:0)

好的,我发现了什么问题。 此处详细介绍了此问题:Write to file with register_shutdown_function

我将在这篇文章中尝试补救,如果不是,我将不得不自己手动调用函数。

此致 Crouz