lowercasename
lowercasename

Reputation: 281

fwrite not fwriting when saving contents of a textarea to a file

I'm making an online text editor - just a simple one for my own stuff. I'm trying to write code to save the contents of a textarea to a file - first the file is opened into the textarea (which works fine), and then I want to save the edited text. The writing isn't working. Here's the important code (my apologies for the mess, it's very early days for me and PHP):

<form method="post" action="<?php echo $_SERVER['$PHP_SELF'];?>">
<textarea rows="30" cols="80" name="textdata"><?=$contents?></textarea>
<br />
<?php
$newcontents = $_POST["textdata"];
$openedfile = fopen($filename, "r");
fwrite($openedfile, "hello");
?>
<input type="submit" name="save" value="Save Changes" />
</form>

I'm sure it's something embarrassingly simple.

Upvotes: 2

Views: 1078

Answers (5)

Jan Dragsbaek
Jan Dragsbaek

Reputation: 8101

I would suggest you to look into file_put_contents, as it simplifies all the fwrite, handle and fclose stuff. It is generally very very easy to use this function. As taken from the documentation:

$file = $filename;
$text .= "Hello\n";
file_put_contents($file, $text);

Upvotes: 0

Muhammad Ummar
Muhammad Ummar

Reputation: 3631

$openedfile = fopen($filename, "r"); you are opening file for read only mode, use r+ instead of r

Upvotes: 0

Narf
Narf

Reputation: 14752

You've opened the file handle in a read-only mode.

Upvotes: 0

Tadej Magajna
Tadej Magajna

Reputation: 2963

 fopen($filename, "r");

is ued only for reading...

Use

fopen($filename, "r+");

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382608

That's because you are opening file in readonly mode using r flag:

$openedfile = fopen($filename, "r");
 -------------------------------^

You should use r+, w or a (append) flag.

See the documentation for more flags/information.

Upvotes: 3

Related Questions