Search code examples
php-5.3fopenfwritefclose

why does PHP fopen + fwrite double document?


I am running PHP Version 5.3.4 with Apache/2.2.17 on Windows 7 Ultimate 32bit (IIS disabled). I been looking at the fopen modes and am well aware of what mode does what, but i can't wrap my finger around why the double posting to the txt file with a single fwrite. I've even tried modes: w and c.

Now I don't care whether the new data coming in is being prepend or appended, just so long as its there in the file without truncating existing data.

The real question is, why does the "a" mode instead of just appending new data, it writes (duplicates) the new data to the file twice before it closes.

In php code:

$fh = "";
if(!($fh = fopen("list.txt","x")) // if file exists, just open for writing (prepend)
   $fh = fopen("list.txt","a"); // if not exist, open just for writing (append)

fwrite($fh,"Somthing\r\n"); // write to file (filehandle, "data")
fclose($fh); // close the file

Results:
Somthing
Somthing

SOLVED: Found the culprit: nothing was wrong with my coding. It was an html validator extension I used for Chromium under Ubuntu 10.04. This extension was apparently causing something similar to instant page reload.


Solution

  • $fh = fopen("list.txt","a");
    fwrite($fh,"Somthing\n"); // write to file (filehandle, "data")
    fclose($fh); // close the file
    

    your logic was not correct.

    that's how its done, i hope it works for you