I have created a small application which writes the contents of the $email
variable into the file mailadressen.txt
. If the file exists, the message "Email address already exists" (E-Mail-Adresse bereits vorhanden) appears. If I change the mail adress and reload the page then it doesn't output nothing. But if I reload it again with the new email address if displays the message "Email address already exists" again.
Can someone give me a tip why it doesn't output anything on the first reload but only on the second reload?
<?php
$email = "Kevin@duck.ente";
// open file and read & write
$handle = fopen ("mailadressen.txt", "a+");
while ( $inhalt = fgets ($handle, 4096 ))
{
$inhalt = trim ( $inhalt );
echo "<li> |". $inhalt ."| </li>";
if ( $inhalt == $email)
{
echo "E-Mail-Adresse bereits vorhanden";
continue;
}
}
fwrite($handle, $email);
// new line
fwrite($handle, "
");
fclose($handle);
?>
Here's one solution based on my comment.
$email = "Kevin@duck.ente";
// open file and read & write
$handle = fopen ("mailadressen.txt", "a+");
while ( $inhalt = fgets ($handle, 4096 )){
$inhalt = trim ( $inhalt );
echo "<li> |". $inhalt ."| </li>";
if ( $inhalt == $email){
$email_exists = true;
$msg = "E-Mail-Adresse bereits vorhanden";
continue;
}
}
//echo the message if email already exists
if(isset($email_exists) && $email_exists === true){
echo $msg;
}
else{
//let's write only non existing email to the file
fwrite($handle, $email);
// new line
fwrite($handle, "
");
echo "Wrote new email: " . $email . " into the mailadressen.txt file.";
}
fclose($handle);