Code: <?php $ourFileName="newfile.txt"; $fh = fopen($ourFileName, 'a+') or die("Can't open file"); echo " File opened: ".ftell($fh); fwrite($fh,"<image></image>"); fseek($fh,-8,SEEK_END); fwrite($fh,"Data Written"); fclose($fh); ?> Whats wrong here? Its output is as follows: Code: <image></image>Data Written Where as expected output is: Code: <image>Data Written</image> Any Suggestions?
Just try the following. Close the file after writing string and then open back to write and see what is the output?
Even after closing the file, output is same. I just forgot to put fclose here. In file, I am using that one. I have edited the post. More over, whenever I re-run the PHP page, it should return the current pointer position which should be the at the end here. But ftell function returns 0 everytime, whether text file has data or not.
When you open the file in append mode it always writes to the end of the file and not where the FILE_POINTER
Sir if so , why ftell() function is always resulting 0 whenever it is re-opened. It should give the last point from where it has to start writing. Moreover I am using fseek() function to move the pointer to -8 from end-of-file.
Probably what I can get is the file is opened and 0 is set at the last or something like that so that you can not do anything to the previous data.
Ok. I used r+ and added some more logic to it. Code: <?php $ourFileName="newfile.txt"; if(is_file($ourFileName)) $fh = fopen($ourFileName, 'r+') or die("Can't open file"); else $fh = fopen($ourFileName, 'w') or die("Can't open file"); fwrite($fh,"<image></image>"); fseek($fh,-8,SEEK_END); fwrite($fh,"Data Written"); fclose($fh); ?> But still I am not getting expected result. now the result is as follows: Code: <image>Data Written [/code]
PHP does not have a function to insert text into the middle of a file and you have to read the complete data and then insert the data in the variables and write it back. Thats the best way to go about getting this done.