Jump to content

Check data / Write Data to a text file


longsack

Recommended Posts

Sorry guys, I'm just learning, i'm sure this is simple....

My script is basically, submit your email address, write the email address to a text file... simple!  I want to check the email address submitted against the text file and if the email address is already located in the text file... display a message "already added"... Here is what I have so far... very simple....

<?php
if(isset($_POST['submit']))
{
    $email = $_POST['email'] . PHP_EOL;
    $file = fopen("emails.txt","a+");
    fwrite($file,$email);
    fclose($file); 
    print_r(error_get_last());
}
?>


<form action= "" method="post" name="form">
<input type="text" name="email">
<br>
<br>
<input type="submit" name="submit" value="submit"><br>
</form>

any thoughts on how to make this happen?

Link to comment
Share on other sites

It's really not that complicated -- a small addition to your existing code:

 

 

$filename = 'emails.txt';
if(isset($_POST['submit']))
{
    $email = trim($_POST['email']);
    $fileString = file_get_contents($filename);
 
    // Check to see if email is already in file. 
    if (false === stristr($fileString, $email)) {
 
        $file = fopen($filename, "a+");
        fwrite($file, $email . PHP_EOL);
        fclose($file);
        echo "Added Email: $email to the system";
        
    } else {
        echo "Email: $email already exists in the system.\n";
    }
}
?>
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.