Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

php - Write to file with 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');
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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');

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...