Nirmal
Nirmal

Reputation: 9549

PHP - Will fwrite() save the file immediately?

This is my code:

$zplHandle = fopen($target_file,'w');
fwrite($zplHandle, $zplBlock01);
fwrite($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.

Upvotes: 11

Views: 7278

Answers (4)

tsgrasser
tsgrasser

Reputation: 712

Assuming your working in PHP 5.x, try file_put_contents() instead, as it wraps the open/write/close into one call. https://www.php.net/manual/en/function.file-put-contents.php

Upvotes: 1

Young
Young

Reputation: 8356

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.

Upvotes: 5

oezi
oezi

Reputation: 51797

the file will be saved on fclose. if you want to put the content to the file before, use fflush().

Upvotes: 4

Sjoerd
Sjoerd

Reputation: 75588

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().

Upvotes: 12

Related Questions