3

In php i am opening a text file and appending to it. However I need to append 3 chars before the end of file. In other words i need to append/write from a specific place in the file.

Can any one help?

Best Regards Luben

2

2 Answers 2

10

You need to open the file for edit, seek to the desired position and then write to the file, eg.:

<?php
  $file = fopen($filename, "c");
  fseek($file, -3, SEEK_END);
  fwrite($file, "whatever you want to write");
  fclose($file);
?>

Further reference at php.net - fseek doc

Hope that helps.

Sign up to request clarification or add additional context in comments.

4 Comments

Sorry but you are wrong! I tried that before I posted here, I should have mentioned that. If you open a file with a or a+ it will append to the end regardless of fseek() or rewind(). Read the notes ant the bottom of the link you posted. Another thing if I use w or w+ it simply starts from the beginning. Any other suggestions?
The bottom of the article also states that by opening the file in 'r+' you should be able to use fseek()
@Luben you are right, I haven't read it properly. The correct mode is "c" or "c+" (or you can use "r+", as @Neil Aitken said :)), as stated in link I have edited the response to reflect it.
@Neil Aitken && @Erbureth Thanks so much for the help guys! You are both right. r+ and c or c+ work perfectly!!
1

If it's a short text file and you are only doing this once you can read in the contents (with fread()), store it only upto 3 chars from the end using substring and then append your new content onto the end of that and write.

But as I say if this is a regular thing and/or with large files, this isn't the best approach. I'll have a think.

Hope this helps

3 Comments

Thanks Alex B! I didn't think of that and it may be a solution. But I'm afraid the files might get pretty big....say up to 1000 chars. If I can't find anything else I'll create a dummy file and do some tests.
@Luben: 1000 characters are around 1kB (in ascii 1 character = 1 Byte). Its safe to read it completely into the memory.
Thanks King! Ideally I want to use Erbureth's method that he mentions above but unfortunately that doesn't work. I will look around and if not tomorrow I'll do as you say.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.