Forum Moderators: coopster

Message Too Old, No Replies

easy php file writing script

         

rokec

3:09 pm on Oct 19, 2006 (gmt 0)

10+ Year Member



I want to make a script, which will add time() at the new line at the begginging of the file (texts/text.txt), every time the user will clik on a submit button;

Sample code:
<?php if (isset($_POST['submit'])){
$statusfile = fopen("texts/text.txt", 'r+') or die("can't open file");
fwrite($statusfile, $_POST['profile']."\n");
}?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<input name="submit" type="submit" value="Submit">
</form>

What's wrong with code?
Isn't the "r+" parameter to open file for reading and writing, with pointer at the begginging of the file?

jatar_k

5:26 pm on Oct 19, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I don't see $_POST['profile'] being set anywhere

you also aren't reading the content from the file, though I am not sure if you want to or not

rokec

6:11 pm on Oct 19, 2006 (gmt 0)

10+ Year Member



oh, in that $_post is stored time():
$_POST['profile']=time();

Can you help me?

jatar_k

6:13 pm on Oct 19, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I don't know what is going wrong

is it not writing anything?

rokec

6:59 pm on Oct 19, 2006 (gmt 0)

10+ Year Member



When i wiev the file, there is just the last line (this script should add, not overwrite)

Birdman

7:58 pm on Oct 19, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Actually, I believe the r+ mode is supposed to overwrite. To get around that, read the existing contents of the file into a var, write the new line, then write the existing to it. See below.

<?php
if (isset($_POST['submit'])){
$file = "texts/text.txt";
$statusfile = fopen($file, 'r+') or die("can't open file");
$existing_file = fread($statusfile, filesize($file));
fwrite($statusfile, $_POST['profile']."\n".$existing_file);
fclose($statusfile); // Don't forget to close!
}?>

jatar_k

10:37 pm on Oct 19, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



>> r+ mode is supposed to overwrite

exactly, it isn't a prepend, it just writes over whatever is there.

you could even do it this way

<?php
if (isset($_POST['submit'])){
$file = "texts/text.txt";
$existing_file = file_get_contents($file);
$statusfile = fopen($file, 'w') or die("can't open file");
fwrite($statusfile, $_POST['profile']."\n".$existing_file);
fclose($statusfile); // Don't forget to close!
}?>

rokec

4:14 am on Oct 20, 2006 (gmt 0)

10+ Year Member



r+ is actually for inserting, but i forgot to close a file...

Birdman

10:10 am on Oct 20, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



r+ is actually for inserting, but i forgot to close a file...

No, r+ will always place the pointer at the beginning of the file and write over any existing data, regardless of whether you forgot to fclose the file.