tags:

views:

22

answers:

2

Hi

i am creating an under construction page where users can leave their email to be notified when the site launch

i need to add those emails to a text file called list.txt

my question is two parts

how can i add [email protected] to the text file ?

and how i can later delete certain email from a text file ?

thanks for help

+1  A: 

As for saving, you can fopen() in appending mode and just fwrite() to it. As for deleting a certain email: you'll have to load the whole file as a string and save it to file (effectively replacing the entire contents). Without some elaborate locking mechanism a race condition can occur when saving the file, causing you to lose the / a latest signup(s).

I would recommend a simple drop-in sqlite database (or another database if you already have one in production), so you can easily save & delete certain emails, and locking / avoiding race conditions is done automatically for you. If you still need a text file for some other purpose, export the subscription list to that file before using it.

Wrikken
+1  A: 

You'd be better off using a database because these operations can step on each other.. but:

Add:

$fp = fopen("list.txt","a");   //a is for append
fputs($fp,"[email protected]" . "\n");
fclose($fp);

Remove:

$file = file_get_contents("list.txt");
unlink("list.txt");  //delete existing file
$fp = fopen("list.txt","w");   //w is for write/new
$lines = split("\n",$file);
while (list(,$email) = each($lines)) {
    if ($email != "[email protected]") fputs($fp,$email . "\n");
}

Again... highly recommended to use a database... this is not optimal.

Fosco
Shortcut for the `file_get_contents()` / `split()` combo is `file()`, with possibly even `$array_of_lines = file('/path/to/file',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);`
Wrikken