Simple PHP text file editor

I was looking around for some VERY simple PHP code that would allow me to edit a text file on a web server.

I came across this code, but for the life of me couldn’t get it to work. It would read the contents of the text file but never modify it.

I don’t know if it’s a PHP dialect issue, but I’ve now got it working on Apache on Mac OS 10.3 with the following tweaks:

if ($submit)
at the top of the original is now
if (($_POST['submit']) == “submit”)
This detects if the form has been submitted; if it has, it then goes on to rewrite the text file.

fwrite($fp, stripslashes($newdata));
is now
fwrite($fp, stripslashes($_POST['newdata']));

Maybe I’m missing something, but it seems logical that a form returns an array, and in order to process the form you need to access the individual elements of the array. Just writing ‘$newdata’ (rather than telling PHP it’s the ‘newdata’ bit of the submitted form) seems too simple!

Anyway, here’s my code. You’ll need a text file in the same directory called data.txt and you’ll need to change its permissions I suppose. I really must read up on Unix permissions and PHP next…

<?php

if (($_POST['submit']) == “submit”) {
$fp = fopen(“data.txt”,”w”);
fwrite($fp, stripslashes($_POST['newdata']));
fclose($fp);
}

// was stripslashes($newdata);

$fp = fopen(“data.txt”,”r”);
while (!feof($fp)) {
$data .= fgets($fp, 4096);
}
fclose($fp);

?>

<html>
<head>
<title>php form test</title>
</head>

<body>

<p>Adapted from http://www.onaje.com/php/article.php4/23
by othermachines.org

<p>The contents of a text file called data.txt is displayed in
the edit window below and you can edit it and save it by
clicking on the Submit button.

<form action=”<? print $PHP_SELF; ?>” method=”post”>
<textarea name=”newdata” rows=”10″ cols=”40″>
<?
print $data;
?>
</textarea>

<input type=”submit” name=”submit” value=”submit”>
</form>

</body>
</html>

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply