your problem in your code is the fwrite function.
fwrite($fp,$counter,sizeof($counter));
in your code, the sizeof( $counter ) will always be 1 because there is only one line in your counter.txt
sizeof -- Alias of count()
because there is only one line in your counter.txt file, so only one item will be available when you use the file function to read. file will read the file into array...
so, your fwrite function will only put 1 byte of data into that counter.txt.
so it is okay for the number to loop from 0 to 9, but when it comes to 10, the fwrite will only write 1 to the file, missing the 0 because you only allowed 1 byte of length to be wrote.
so, the solution is,
fwrite( $fp, $counter );
so the fwrite will write all the bytes in the $counter to the file.
read the manual... read it and read it again ....