Simple PHP Text Editor

November 1st, 2009 by Alex Leave a reply »

Let’s start from creating our html form for uploading the changes. Imagine our editor script filename is editor.php and the page we need to edit is called page.html. Let’s create the vars:

<?
$page = 'page.html';
?>
<form action='editor.php' method='post'>
 <textarea name='content' style='width: 100%; height: 300px'><?=file_get_contents($page)?></textarea>
 <br /><br />
 <input type='submit' value='save' />
</form>

In this short sample we see that we include the contents of $page in textarea, showing the current page.html content. Now, let’s make the script check if the editor uploaded the new content. Add these lines right after $page = ‘page.html’

if (isset($_POST['content'])) {
 $fp = fopen($page, 'w');
 if ($fp) {
  fwrite($fp, str_replace(array('\"',"\\'"), array('"', "'"), $_POST['content']));
  fclose($fp);
  echo '<strong>File saved ok.</strong>';
 } else
  echo '<strong>Error! File not saved.</strong>';
}

As from PHP 5.3.0, magic quotes is deprecated, and is removed from 6.0,  so we replace the \’ and \” in content with single quotes. If file is opened, then echo the success string, else echo that something is wrong. Feel free to comment if you have any questions.

NOTES:

  • Don’t forget to chmod 666 the page which is edited
  • Make sure that php magic_quotes is off

Comments are closed.