gpt4 book ai didi

php - 使用register_shutdown_function写入文件

转载 作者:行者123 更新时间:2023-12-02 23:45:07 25 4
gpt4 key购买 nike

是否可以执行以下操作?

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。

最佳答案

这取决于您使用的 SAPI。 documentation page for register_shutdown_function()指出在某些服务器(例如 Apache)下,脚本的工作目录会发生变化。

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

为了防止这种情况,您需要以某种方式热线更改工作文件夹。当你的脚本开始执行时(在前几行),你需要以某种方式存储真正的工作文件夹。使用 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()。这就是为什么我把它写在函数代码的下面,而不是上面。

关于php - 使用register_shutdown_function写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10861606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com