editing a .txt file with php

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mccommunity
Forum Commoner
Posts: 62
Joined: Mon Oct 07, 2002 8:55 am

editing a .txt file with php

Post by mccommunity »

I have a .txt file on my server and I need to somehow build an interface that will open this and let the user type in new data then resave it with the changes. How would I do this?

Thanks
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

mccommunity
Forum Commoner
Posts: 62
Joined: Mon Oct 07, 2002 8:55 am

confusing

Post by mccommunity »

This is a bit confusing to me. Does anyone have a script I can look at to see how this is done.
mccommunity
Forum Commoner
Posts: 62
Joined: Mon Oct 07, 2002 8:55 am

I tried this

Post by mccommunity »

I tried to use the code below that I came up with. This does not work it give me errors, I did set the permissions on the file and directory to chmod 777:




Warning: fwrite(): supplied argument is not a valid stream resource in /usr/www/users/development/php/text editor/test.php on line 40

Warning: fclose(): supplied argument is not a valid stream resource in /usr/www/users/development/php/text editor/test.php on line 41




<html>

<?php
$filename="text.txt";

// Gets webpage into a string
$html = implode('', file('text.txt'));
echo $html;


?>


<body>
<form name="form1" method="post" action="test.php">
<textarea name="newfile" cols="30" rows="10"><? echo $html; ?></textarea>
<input type="submit" name="submit" value="submit">
</form>




</html>


<?

if ($submit)
{
$file = "$filename";
$fh = fopen($file, 'w+');
fwrite($fh, $newfile);
fclose($fh);


}






?>
User avatar
DuFF
Forum Contributor
Posts: 495
Joined: Tue Jun 24, 2003 7:49 pm
Location: USA

Post by DuFF »

A few problems with that code, check out my comments:

Code: Select all

<html>
<?php

$filename="text.txt";
// Gets webpage into a string
$html = implode('', file('text.txt'));
echo $html;

?>
<body>
<form name="form1" method="post" action="test.php">
<textarea name="newfile" cols="30" rows="10"><? echo $html; ?></textarea>
<input type="submit" name="submit" value="submit">
</form>
</html>
<?

if (isset($_POST["submit"]))  // notice the addition of $_POST!  read below for more info
{

// $file = "$filename";  what is the point of this line? You've already got the name in a variable
$handle = fopen($filename, 'w+');
fwrite($handle, $newfile);
fclose($handle);

}
?>
If you don't have register_globals enabled (which you shouldn't), the if($submit) is not the correct way to write it. Because you are passing the form info using the POST method, you want to use the post superglobal.
Post Reply