Search code examples
phpunlink

how to delete a single line in a txt file with php


i was wondering if it is posible to delete a single line in a txt file with php.

I am storing emailadresses in a flat txt file named databse-email.txt

I use this code for it:

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
   $email = $_POST['email-subscribe'] . ',' . "\n";
   $store = file_put_contents('database-email.txt', $email, FILE_APPEND | LOCK_EX);
   if($store === false) {
     die('There was an error writing to this file');
   }
   else {
     echo "$email successfully added!";
   }
}

?>

Form:

<form action="" method="POST">
   <input name="email-subscribe" type="text" />
   <input type="submit" name="submit" value="Subscribe">
</form>

The content of the file looks like this:

janny@live.nl,
francis@live.nl,
harry@hotmail.com,
olga@live.nl,
annelore@mail.ru,
igor@gmx.de,
natasha@hotmail.com,
janny.verlinden@gmail.com,

All lines are , seperated

Lets say i want to delete only the emailadres: igor@gmx.de

How can i do that?

What i want to achieve is a unsubscribe form and delete a single line in the .txt file


Solution

  • You can use str_replace

    $content = file_get_contents('database-email.txt');
    $content = str_replace('igor@gmx.de,', '', $content);
    file_put_contents('database-email.txt', $content);