When I open a file in the 'a' or 'a+' mode , a ftell() displays the file pointer at 0 and not at the end of the file. Any idea why this happens ?
The manual, of all places, says this about that:
ftell() gives undefined results for append-only streams (opened with "a" flag).
And it says the same about "fseek()":
fseek() gives also undefined results for append-only streams (opened with "a" flag).
If you open with "r+" then set the position with "fseek($n)" you can write to that position. Unfortunately, that overwrites the next strlen characters, instead of pushing everything back.
So...read the first n-1 characters into a string, and the rest into another string, then concatenate, with your string to insert between the two.
function fwrite_to_offset($file, $str, $offset)
{
$contents = file_get_contents($file);
$part_1 = substr($contents, 0, $offset);
$part_2 = substr($contents, $offset);
$new = $part_1 . $str . $part_2;
$fp = fopen($file, 'w');
fwrite($fp, $new);
fclose($fp);
}
(Add your own error checking.)