PHP - Will fwrite() save the file immediately?
This is my code:
$zplHandle = fopen($target_file,'w');
fwrite($zplHandle, $zplBlock01);
fwrit开发者_C百科e($zplHandle, $zplBlock02);
fwrite($zplHandle, $zplBlock03);
fclose($zplHandle);
When will the file be saved? Is it immediately after writing to it or after closing it?
I am asking this because I have Printfil listening to files in a folder and prints any file that is newly created. If PHP commits a save immediately after fwrite
, I may run into issues of Printfil not capturing the subsequent writes.
Thank you for the help.
PHP may or may not write the content immediately. There is a caching layer in between. You can force it to write using fflush(), but you can't force it to wait unless you use only one fwrite().
I made a tiny piece of code to test it and it seems that after fwrite
the new content will be detected immediately,not after fclose
.
Here's my test on Linux.
#!/usr/bin/env php
<?php
$f = fopen("file.txt","a+");
for($i=0;$i<10;$i++)
{
sleep(1);
fwrite($f,"something\n");
echo $i," write ...\n";
}
fclose($f);
echo "stop write";
?>
After running the PHP script ,I use tail -f file.txt
to detect the new content.And It shows new contents the same time as php's output tag.
the file will be saved on fclose. if you want to put the content to the file before, use fflush().
Assuming your working in PHP 5.x, try file_put_contents() instead, as it wraps the open/write/close into one call. http://us3.php.net/manual/en/function.file-put-contents.php
精彩评论