使用register_shutdown_function写入文件 [英] Write to file with register_shutdown_function

查看:66
本文介绍了使用register_shutdown_function写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以执行以下操作?

Is it possible to do the following?

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上.

Doesn't seem to work. BTW i'm on PHP 5.3.5.

推荐答案

这取决于您所使用的SAPI. 文档页面指出,在某些服务器(例如Apache)下,脚本目录更改.

It depends which SAPI you are using. The documentation page for register_shutdown_function() states that under certain servers, like Apache, the working directory of the script changes.

文件被写入,但不是您的.php文件( DocumentRoot )所在的位置,而是在Apache服务器的文件夹( ServerRoot )中.

The file gets written, but not where your .php file is (DocumentRoot), but in the folder of the Apache server (ServerRoot).

为防止这种情况,您需要通过某种热线方式更改工作文件夹.刚您的脚本开始执行时(在前几行中),您需要以某种方式存储实际的工作文件夹.为此,使用define()创建一个常数非常合适.

To prevent this, you need to some sort of hotwire the working folder changes. Just when your script starts executing (in the first few lines), you need to somehow store the real working folder. Creating a constant with define() is perfect for this.

define('WORKING_DIRECTORY', getcwd());

并且您需要像这样修改关闭功能部分:

And you need to modify the shutdown function part like this:

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 文件夹中.

This way, the working folder will instantly be changed back to the real one when the function is called, and the test.txt file will appear in the DocumentRoot folder.

一些修改:最好在声明该函数之后调用register_shutdown_function() .这就是为什么我在功能代码的下方而不是上方编写它的原因.

Some modification: It is better to call register_shutdown_function() after the function has been declared. That's why I wrote it below the function code, not above it.

这篇关于使用register_shutdown_function写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆