Search code examples
phpeditfopentext-filesfwrite

replace or delete line in txt file


comm.php

<?
$com = $req_user_info['comments'];
$name = $username;

if($_POST) {
$postdate = date("d M y h:i A");
$content = $_POST['commentContent'];
$handle = fopen("$com","a");
fwrite($handle,"<b>" . $name . "</b>:<br>" . $content . "<br>" . $postdate . "<br>"); 
fclose($handle);}
?>

<html>
<body>
<form action = "" method = "POST">
Post a Comment<br><textarea rows="10" cols="30" name="commentContent"></textarea><br>
<input type="submit" value="Comment"><p>
Comments<p>
<? 
include($com);
?>
</body></html>

/*$req_user_info['comments']; = data.txt*/

data.txt

Alex: sometext 20 Feb 12 11:11 AM
Alex: sometext 20 Feb 12 11:38 AM

What I want to do is delete (or replace with nothing) name, content and postdate.

Example:

Alex: sometext 20 Feb 12 11:11 AM Delete

Alex: sometext 20 Feb 12 11:38 AM Delete

So after I click delete and refresh the page I want the line to be gone.


Solution

  • Instead of just including the file normally, you could use fgets to read line by line (http://www.php.net/manual/en/function.fgets.php). Store each line number as you iterate though, then on your delete link, pass the line number.

    <a href="page.php?delete=XXX">Delete</a>
    

    When you then want to delete, simple go through each line and rewrite the file, skipping the line that was given with the delete link variable $_GET['delete']. Just make sure you're counting as you write each new line so you know when to skip a line.

    Using the PHP example:

    <?php
        $counter = 0;
        $handle = @fopen("/tmp/inputfile.txt", "r");
        if ($handle) {
        while (($buffer = fgets($handle, 4096)) !== false) {
            $counter++;
            echo $buffer . '<a href="page.php?delete='.$counter.'">delete</a>';
        }
        if (!feof($handle)) {
            echo "Error: unexpected fgets() fail\n";
        }
        fclose($handle);
    }
    ?>