Web Form E-Mailed and dumped into a CSV File

Somewhere on here is my question for ASP, but I cannot find it.

In any event, when someone completes a form,  I would like it to be dumped into a CSV file.  If I remove that file, then it creates a new one and starts over

Thank you!
LVL 29
coreybryantAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris StanyonWebDevCommented:
Do you know how to do any of the above? Do you already have some code in place that's giving you errors?

These three function will get you going

file_exists() //does a file exist
fopen() // open (or create) a file
fputcsv() //write CSV formatted data

To find older questions you've asked go to your profile, click on activity and you'll see all your question (640+ of them!)
0
Ray PaseurCommented:
fopen() has flags that allow you to append to an existing file or overwrite the file.
http://php.net/manual/en/function.fopen.php

While it would not be very secure, you can apply fputcsv() to any array, including $_POST.
http://php.net/manual/en/function.fputcsv.php

If you want to post the HTML form we can probably show you how to extend this script to write the CSV.  This script shows the general design of a form-to-email.

<?php // RAY_form_to_email.php
error_reporting(E_ALL);


// SEND MAIL FROM A FORM


// REQUIRED VALUES ARE PREPOPULATED - CHANGE THESE FOR YOUR WORK
$from = 'NoReply@Your.org';
$subj = 'Contact Form';

// THIS IS AN ARRAY OF RECIPIENTS - CHANGE THESE FOR YOUR WORK
$to[] = 'You@Your.org';
$to[] = 'Her@Your.org';
$to[] = 'Him@Your.org';
$to[] = 'Ray.Paseur@Gmail.com';


// IF THE DATA HAS BEEN POSTED (AT LEAST SOMETHING IN THE EMAIL INPUT CONTROL)
if (!empty($_POST['e']))
{
    // CLEAN UP THE POTENTIALLY BAD AND DANGEROUS DATA
    $safe_mail = clean_string($_POST['e']);
    $safe_name = clean_string($_POST['n']);
    $safe_fone = clean_string($_POST['t']);
    $save_idea = clean_string($_POST['i']);

    // CONSTRUCT THE MESSAGE THROUGH STRING CONCATENATION
    $content    = NULL;
    $content   .= "You have a New Query From $safe_name" . PHP_EOL . PHP_EOL;
    $content   .= "Tel No: $safe_fone" . PHP_EOL;
    $content   .= "Email: $safe_mail" . PHP_EOL;

    // SEND MAIL TO EACH RECIPIENT
    foreach ($to as $recipient)
    {
        if (!mail( $recipient, $subj, $content, "From: $from\r\n"))
        {
            echo PHP_EOL . "<br/>MAIL FAILED FOR $recipient";
        }
        else
        {
            echo PHP_EOL . "<br/>MAIL WORKED FOR $recipient";
        }
    }

    // PRODUCE THE THANK-YOU PAGE
    echo '<p>THANK YOU</p>' . PHP_EOL;
    die('TASK COMPLETE');
}


// A FORM TO TAKE CLIENT INPUT FOR THIS SCRIPT
$form = <<<ENDFORM
<form method="post">
Please enter your contact information
<br/>Email: <input name="e" />
<br/>Phone: <input name="t" />
<br/>Name:  <input name="n" />
<br/>Ideas? <textarea name="i"></textarea>
<br/><input type="submit" />
</form>
ENDFORM;

echo $form;


// A FUNCTION TO CLEAN UP THE DATA - AVOID BECOMING AN OPEN-RELAY FOR SPAM
function clean_string($str)
{
    // IF MAGIC QUOTES IS ON, WE NEED TO REMOVE SLASHES
    $str = stripslashes($str);

    // REMOVE EXCESS WHITESPACE
    $rgx
    = '#'                // REGEX DELIMITER
    . '\s'               // MATCH THE WHITESPACE CHARACTER(S)
    . '\s+'              // MORE THAN ONE CONTIGUOUS INSTANCE OF WHITESPACE
    . '#'                // REGEX DELIMITER
    ;
    $str = preg_replace($rgx, ' ', $str);

    // REMOVE UNWANTED CHARACTERS
    $rgx
    = '#'                // REGEX DELIMITER
    . '['                // START OF A CHARACTER CLASS
    . '^'                // NEGATION - MATCH NONE OF THE CHARACTERS IN THIS CLASS
    . 'A-Z0-9'           // KEEP LETTERS AND NUMBERS
    . '"'                // KEEP DOUBLE QUOTES
    . "'"                // KEEP SINGLE QUOTES
    . '@&+:?_.,/\-'      // KEEP SOME SPECIAL CHARACTERS (ESCAPED HYPHEN)
    . ' '                // KEEP BLANKS
    . ']'                // END OF THE CHARACTER CLASS
    . '#'                // REGEX DELIMITER
    . 'i'                // CASE-INSENSITIVE
    ;
    $str = preg_replace($rgx, NULL, $str);

    // REMOVE EXCESSIVE INPUT
    $str = substr($str, 0, 255);

    return trim($str);
}

Open in new window

This example shows another take on it.

<?php // RAY_form_to_csv.php // PHP 5+
error_reporting(E_ALL);

// IF ANYTHING HAS BEEN POSTED
if (!empty($_POST))
{

    // ADD FILTER AND VALIDATION CODE HERE FOR NAME AND EMAIL
    $f = $_POST["f"];
    $l = $_POST["l"];
    $e = $_POST["e"];
    $txt = array($e, $f, $l);

    // CREATE AND WRITE A SAFEKEEPING COPY OF THE CSV FILE
    $csv = 'my.csv';
    $fpo = fopen($csv, 'w');
    fputcsv($fpo, $txt);
    fclose($fpo);

    // READ THE CSV FILE FOR USE IN AN ATTACHMENT
    $fpo   = fopen($csv, 'rb');
    $fdata = fread($fpo, filesize($csv));
    fclose($fpo);

    // VARIABLES FOR THE EMAIL
    $to    = "You@Your.org";
    $from  = "Whoever@Your.org";
    $subj  = "CSV ATTACHED";

    // VARIABLES FOR THE ATTACHMENT
    $ftype = "text/csv";
    $fname = "registration.csv";

    // CREATE THE HEADERS
    $head  = "From: $from\n";
    $head .= "MIME-Version: 1.0\n";
    $head .= "Content-Type: multipart/mixed; boundary=\"edge_of_night\"\r\n";

    // CREATE THE EMAIL AND THE ATTACHMENT
    $message = '';
    $message .= "This is a multi-part message in MIME format.\n\n";
    $message .= "--edge_of_night\n";
    $message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
    $message .= "Content-Transfer-Encoding: 7bit\n\n";
    $message .= "\n\n";
    $message .= "--edge_of_night\n";
    $message .= "Content-Type: {$ftype}; name=\"{$fname}\"\n";
    $message .= "Content-Disposition: attachment; filename=\"{$fname}\"\n";
    $message .= "Content-Transfer-Encoding: base64\n\n";

    $fdata = chunk_split(base64_encode($fdata));

    $message .= $fdata . "\n\n";
    $message .= "--edge_of_night\n";

    // SEND THE MESSAGE AND ATTACHMENT
    mail($to, 'CSV ATTACHED', $message, $head);

} // END OF PHP PROCESSING THE POSTED FORM - PUT UP THE HTML FORM FOR INPUT

?>
<form method="post">
FIRST NAME: <input name="f" /><br/>
LAST NAME:  <input name="l" /><br/>
EMAIL ADDR: <input name="e" /><br/>
<input type="submit" />
</form>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
coreybryantAuthor Commented:
Thanks - I don't but have someone to do it.

Ray_Paseur
On the ASP one that I had, if the CSV file was not there, it would recreate it.  Will this do the same thing?

Thank you!
0
Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

Ray PaseurCommented:
Given that question, I would recommend that you step back from trying to do this yourself and hire a professional developer.  Maybe someone from eLance.com.  There are many moving parts to this, and your application security needs professional attention.  You cannot get that from the back-and-forth in an online forum.  I wish I could help, but this is not a question with any one answer anymore -- it's a requirement for application development and for that you need the services of a professional application developer.

Best regards, ~Ray
0
coreybryantAuthor Commented:
I'll just erase the CSV file to see if that works, I apologize the offense.
0
Ray PaseurCommented:
I'm not offended at all; I just have been in this business a long time and when I see someone about to get in too deep I try to guide in the direction of getting professional help.  Best of luck with the project, ~Ray
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.