PHP fwrite over itself
<p>I'm working on a little experiment here. I've got a test file that I use to run some code without having to actually log into my app.</p>

<p>At any rate, I had a thought today that I could potentially make the page self-editing and make it quicker for me to do certain menial tasks as I wouldn't even need to open up a text editor for them.</p>

<p>It's <em>mostly</em> working as it sits, but I'm getting a weird thing; I'm hoping either someone just happens to have experience with or can shed some light on.</p>

<p>I won't post the code for the entire file, just the relevant stuff. Here's the basic idea:</p>

<p>index.php:</p>

<pre><code>&lt;?php
if(isset($_POST['file'])) {
  // rewrite ourself
  $test_page = fopen('index.php', 'w');
  fwrite($test_page, $_POST['file']);
  fclose($test_page);
  header('Refresh: 0; ' . $_SERVER['PHP_SELF']);
  exit();
  die(); // we should never get this far...
}
?&gt;
&lt;?php &lt;!-- All the tester stuff goes here --&gt; ?&gt;
&lt;?php &lt;!-- Nothing fancy just a bunch of function calls --&gt; ?&gt;
&lt;!doctype html&gt;
&lt;html lang="en"&gt;
  &lt;head&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div&gt;
      &lt;!-- a dump of the functions called in the tester area --&gt;
    &lt;/div&gt;
    &lt;div&gt;
      &lt;form method='post'&gt;
        &lt;textarea name='file'&gt;
&lt;?php
$self = fopen('index.php', 'r');
while(!feof($self)) {
  echo fgets($self);
}
fclose($self);
?&gt;
        &lt;/textarea&gt;
        &lt;input type="submit" value="Edit/Refresh"&gt;
      &lt;/form&gt;
    &lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>Now everything is working just great, except that the last 5 HTML tags are not being written to the file; or more accurate, the last 5 HTML tags are not being written into the <code>textarea</code> So when it comes time to save, after the submit, they obviously are not being appended. My theory so far is that once the  tag is output by PHP, it obviously closes the text area... so I need to find a way to get that closing tag inside the textarea. I verified this by viewing the source of the page, so I think it's correct.</p>

<p>So I think I just need a way to 'escape' them... </p>

<p>I know it's not a good thing in terms of security, but this is just a local page that I use (it's not available to anyone except the person sitting at my computer). So we don't need to discuss the security issues it obviously may have...</p>

<p>All thoughts appreciated! :)</p>
