I have the following code and a text file with contents of "test1-test70" but for some reason when I enter test1 it deletes test1-10. how do I limit it to delete specifically what I tell it to?

here is the code.

<?
$filename = "./foo.txt";
$fd = fopen ($filename, "r");
?>

<form action=test.php method=post>
Name to be deleted: <input type=text name=DELETE value="">
<input type=submit name=submit value="DELETE USER">

<?
if ($submit)
{
echo"<br><br><b>DELETING: $DELETE</b><br><br>";
$m_line=0;$tmp_line=0;$line=0;
$m_filename = "./foo2.txt";
$m_fd = fopen($m_filename, "w");
while (!feof ($fd)){
$buffer = fgets($fd, 4096);
$pos = strpos ($buffer,$DELETE);
if ($pos === false and $line==0){
fputs ($m_fd,$buffer);
}
else{
if ($tmp_line < $m_line){
$tmp_line = $tmp_line + 1;
$line = 1;
}
else{
$line = 0;
echo "<b>DELETED: $DELETE</b><br><br>";
}
}
}
fclose($fd);
fclose($m_fd);
copy("./foo2.txt","./foo.txt");
}
?>

    i would do this:

    
    $DELETE = "line1";
    
    $data = file("./foo.txt");
    
    $out = array();
    
    foreach($data as $line) {
        if(trim($line) != $DELETE) {
            $out[] = $line;
        }
    }
    
    $fp = fopen("./foo.txt", "w+");
    flock($fp, LOCK_EX);
    foreach($out as $line) {
        fwrite($fp, $line . "\r\n");
    }
    flock($fp, LOCK_UN);
    fclose($fp);
    

    basically this will just look over every line and if it not what you want to delete, it gets pushed to an array that will get written back to the file.

      works great! thanks for the coding.

      I had to remove the \r\n as it was causing a double space between lines in the new text file but other than that it works just like I wanted it to!

        yeah you are right, i didnt actually trim the $line for putting in the array just comparing, so taking that \r\n out was good. glad it works for you.

          Write a Reply...