Page 1 of 1

Help with function code

Posted: Sat Apr 26, 2008 5:48 pm
by ggrant3
I would like to have a function that takes the customers email address from a certain field, check to make sure the email does not already exist, and if it does not then store the email into a file.

But I am still new to php and I am not sure if what I have so far is correct or even what else needs to be added.

Also where in the script should I place this code?

Code: Select all

<?php
// Define filename and open in read-write append mode
    $filename = 'C:/private/customeremail.txt';
    $file = fopen($filename, 'a+');
    // If filesize is zero, no names yet registered
    // So just write the customer email to file
    if (filesize($filename) === 0) {
      fwrite($file, "$email");
      }
     // If filesize is greater than zero, check customer email first
     else {
        // Move the internal pointer to the beginning of file
        rewind($file);
        // Loop through file one line at a time while (!feof($file)) {
            $line = fgets($file);
            // Split line at comma, and check first element against customer email
            $tmp = explode(', ', $line);
 
// close the file
fclose($file);
}
}
That is all I have been able to come up with so far.

Re: Help with function code

Posted: Sun Apr 27, 2008 2:32 am
by nowaydown1
Hey ggrant3. I think that you were taking steps in the right direction with this. You mentioned in your post that you were new to PHP, so I decided to put some sample code together for you in the hopes that it will "click" when you see it. There's plenty of different ways you could go about solving your problem, but this is what I came up with:

Code: Select all

 
<?php
 
/**
 * Adds a new email address to the customer storage file ($storageFile).  
 * The email address will be stored as lowercase with this function.
 * 
 * @param string $emailAddress - (e.g. 'bob@anexample.com')
 * @param string $storageFile - (e.g. '/tmp/myfile.txt')
 * @return bool - true upon success
 */
function addCustomerEmailToFile($emailAddress, $storageFile) {
    
    /* We create an array to store the existing customer email address for comparison. */
    $existingCustomerEmailAddresses = array();
    $fileContents = ""; 
    
    /* If the file already exists on the disk, then we should read it. */
    if(file_exists($storageFile)) {
        if(!$fileContents = file_get_contents($storageFile)) {
            die("An error occured while trying to read the customer storage file $storageFile.");
        }
    }
    
    /* Then, we open the file $storageFile for append mode. */
    if(!$fileHandle = fopen($storageFile, "a")) {
        die('Could not open customer storage file.');
    }
        
    /* We explode on newline characters since we store one email address per line. */
    if(!empty($fileContents)) $existingCustomerEmailAddresses = explode("\r\n", $fileContents);
    
    /* We're only going to add the email address if it doesn't already exist in the file. */
    if(!in_array(strtolower($emailAddress), $existingCustomerEmailAddresses)) {
        if(fwrite($fileHandle, strtolower($emailAddress)."\r\n") === false) {
            die('An error occured while writing to the customer storage file.');
        }
    }
    
    /* Finally close the file handle. */
    fclose($fileHandle);
    return true;
}
 
if(isset($_POST["btnAdd"])) {
    if(addCustomerEmailToFile($_POST["emailAddress"], "customer_emails.txt")) {
        echo "Processed customer email address for " . $_POST["emailAddress"];
    }
}
 
?>
 
<form name="frmAddEmail" action="<?php print($_SERVER["PHP_SELF"]); ?>" method="post">
    <input type="textbox" name="emailAddress" />
    <input type="submit" name="btnAdd" value="Add Email Address" />
</form>
 
Essentially, the above reads the file contents into an array should it already exist on the disk. Then, prior to writing the new address to the file, an in_array check happens to see if that email address was already present in the array we loaded up earlier. I'm using strtolower at the time of writing and comparison to remove any uppercase/lowercase comparison issues.

I'm not sure what sort of project you are working on, but is there a reason that the email addresses need to be stored in a flat file? It seems like a database could be a better option depending on your needs.

I would encourage you to use the above code as a rough picture of one way that your task could be accomplished. If you were going to write this for a production environment, I would highly recommend you to take the necessary steps to make the above code a little more secure.

Anywho, I hope this helps you out :o

Re: Help with function code

Posted: Sun Apr 27, 2008 7:41 pm
by codeblock
Just made this real quick. Get the user input to $email then apply this function to it... It's untested:

Code: Select all

 
$emaildatabase = "file";
function email_check($email){
     if(preg_match("/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/i",$email){
          // If its a valid email
          $database = file($emaildatabase);
          foreach($database as $line){
               if($line == $email){
                   // if its already in the database
                    echo "This email address has already been entered in the database";
               } else { // otherwise its ok, so add it.
                    file_put_contents($emaildatabase,$email."\n");
                    echo "Added email to the database.";
               }
      } else { //not a valid email
         echo "Not a valid email."
         die();
//end of function
}
 
 
again.. this is untested but should work.