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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.