Search code examples
phpformssessionunset

How can I unset a line in PHP after pressing a submit button?


I have this code now, but whenever I get to the page my entire text.txt file gets deleted. I am using sessions to get the information from a page from another php document. This is the 3rd page it directs to after information is input.

I would like choose which line to delete from the text file from an input form, but I cannot seem to get it working. Any suggestions? thanks

<?php 
$tekstFil = fopen("test.txt","r");
$t = 0;
while (!feof($tekstFil)) {

  $informasjonLinje = fgets ($tekstFil);

  echo "$t : $informasjonLinje <br/>";

  $t++;
}

fclose($tekstFil);

$fil = file("test.txt");

echo "<br/>";

echo "<form action='' type='get'>";
  echo "Velg hvilken linje med informasjon du vil slette: ";
  echo "<input type='number' name='linjeNummer' value=''>";
  echo "<input type='submit' name='slett' value='slett'>";
echo "</form>";

if(isset($_GET["slett"])) {
  echo "Du valgte å slette linje nummer: " .  $_GET["linjeNummer"];
}

$linjeNummer = $_GET["linjeNummer"];

  unset($fil[4]);

$fil = array_values($Fil);
$tekstFil = fopen("test.txt", "w");

foreach ($fil as $verdi) {
  fwrite($tekstFil, $verdi);
}
fclose($tekstFil);

Solution

  • Please try this code. There could be much simpler ways but just modified your code

    <?php 
    
    $tekstFil = fopen("test.txt","r");
    $t = 0;
    $buffer = array();
    while (!feof($tekstFil)) {
    
      $informasjonLinje = fgets ($tekstFil);
      $buffer[] = $informasjonLinje;
    
      echo "$t : $informasjonLinje <br/>";
    
      $t++;
    }
    
    fclose($tekstFil);
    
    $fil = file("test.txt");
    
      echo "<br/>";
      echo "<form action='' type='get'>";
      echo "Velg hvilken linje med informasjon du vil slette: ";
      echo "<input type='number' name='linjeNummer' value=''>";
      echo "<input type='submit' name='slett' value='slett'>";
      echo "</form>";
    
    if(isset($_GET['slett'])) {
        echo "Du valgte å slette linje nummer: " .  $_GET["linjeNummer"];
        $linjeNummer = $_GET["linjeNummer"];
        //unset($fil[4]);
    
        //$fil = array_values($Fil);
    
        $tekstFil = fopen("test.txt", "w");
        unset($buffer[$linjeNummer]); 
        $buffer1 = implode("", $buffer);
        fwrite($tekstFil, $buffer1);        
        fclose($tekstFil);
    }      
    unset($buffer);
    

    ?>

    Please try not to reload the page since you're used GET method.