Jump to content

edit local txt files

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
mayo

mayo

    Newbie

  • Members
  • PipPip
  • 15 posts
Hi. I was wondering how to EDIT local txt files with a .php script. Instead of overwriting current files, I want to add text in a new line, to whatever is already in the file.

I'm receiving a variable with the POST method, and i wish to add whatever string of text is in that variable, in a new line, in a certain text file.

Thanks in advance. :)

#2
linuxprogramming4ever

linuxprogramming4ever

    Newbie

  • Members
  • PipPip
  • 10 posts
This should do it

<?php
$fid = fopen('fileName.txt', 'a') or die("Can't open file"); //open file in appending mode
fwrite($fid, $_POST["var"]); //write text to the end of file.
fclose($fid);
?>

Depending on your website you might want to protect against "evil" user-input in the $_POST["var"], if you know what I mean.

#3
so1i

so1i

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 312 posts
You can use the fopen() command, but append 'a', where you could append 'r' or 'w' etc.
Appending 'a' means that it can write to the file, but that the data in the file is preserved, so it begins writing at the end of the file, rather than overwriting it.


fopen($filename,'a');


Obviously, just as you can use r+ for both reading and writing, you can use a+ in the same way, the only difference being it writes from the end of the file.

Hope this helps!

#4
mayo

mayo

    Newbie

  • Members
  • PipPip
  • 15 posts
thanks, it works :)

but does it also create the file if it doesn't already exist? If not, how do I go about doing that?

#5
so1i

so1i

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 312 posts

mayo said:

thanks, it works :)

but does it also create the file if it doesn't already exist? If not, how do I go about doing that?

If the file is not already there, it creates it and adds the text to the beginning of the file. :)