Frank Frank - 5 months ago 16
PHP Question

Php code to modiy a file content

I have been trying to modify a file in a directory using php, but it end up adding new content to the old file content. i don't know what again to do so i can modify the whole content without merging to with old one

here is what i tried to use

<?php

$fn = "mod.php";
$file = fopen($fn, "a+");
$size = filesize($fn);
$filecontent = $_POST['addition'];

if($_POST['addition']) {
fwrite($file, $_POST['addition']);
}

$text = fread($file, $size);
fclose($file);

?>

<form action="<?=$PHP_SELF?>" method="post">
<input type="text" name="addition" value="<?php echo $fn;?>"/><br/>
<textarea name="addition"><?php echo $text;?></textarea><br/>
<input type="submit" value="update"/>
</form>

Answer

You can modify it by using the str_replace() function to replace the old file content with the new one.

<?php
  $fn = "mod.php";
  $file = fopen($fn, "a+");
  $handle = fopen($fn, "r");
  $size = filesize($fn);
  $content = fread($handle,$size);
  $text = fread($handle,$size);


  if(isset($_POST['addition'])) {
      $text = fread($file,$size);
      $addition = $_POST['addition'];
      $content = str_replace("$text", "$addition", $file); //$text can be content stored in the database while addition could be the replacement or new content.
      $handle = fopen($fn,"w");
      fwrite($handle,$content);
      fclose($handle);
  }
  ?>
  <form action="" method="post">
  <input type="text" name="addition" value="<?php echo $fn;?>"/><br/>
  <textarea name="addition"><?php echo $text;?></textarea><br/>
  <input type="submit" value="update"/>
  </form>