?
Solved

help modify this script to send .CSV file as email attachment on form submit

Posted on 2016-09-03
7
Medium Priority
?
51 Views
Last Modified: 2016-10-24
I have this code working properly to output a .csv file into the browser download queue on form submit, but what I really need it to do is to send the csv file as an email attachment to  a specific email address instead of downloading in browser...

It's been suggested that I just have the csv save on the server and then email a link, but I need the csv attached to the email that gets sent on submit.

If someone can help me with that code, that would be AWESOME!
<?php
if(isset($_POST['submit'])){

    //collect form data
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $title = $_POST['title'];
    $phone = $_POST['phone'];
    $fax = $_POST['fax'];
    $email = $_POST['email'];

    //check name is set
    if($firstName ==''){
        $error[] = 'Name is required';
    }

    //check for a valid email address
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
         $error[] = 'Please enter a valid email address';
    }

    //if no errors carry on
    if(!isset($error)){

        # Title of the CSV
        $Content = "firstName, lastName, title, phone, fax, email\n";

        //set the data of the CSV
        $Content .= "$firstName, $lastName, $title, $phone, $fax, $email\n";

        # set the file name and create CSV file
        $FileName = "formdata-".date("d-m-y-h:i:s").".csv";
        header('Content-Type: application/csv'); 
        header('Content-Disposition: attachment; filename="' . $FileName . '"'); 
        echo $Content;
        exit();
    }
}

//if their are errors display them
if(isset($error)){
    foreach($error as $error){
        echo "<p style='color:#ff0000'>$error</p>";
    }
}
?> 

<form action='' method='post'>
<p><label>First Name</label><br><input type='text' name='firstName' value=''></p> 
<p><label>Last Name</label><br><input type='text' name='lastName' value=''></p> 
<p><label>Title</label><br><input type='text' name='title' value=''></p> 
<p><label>Phone</label><br><input type='text' name='phone' value=''></p> 
<p><label>Fax</label><br><input type='text' name='fax' value=''></p> 
<p><label>Email</label><br><input type='text' name='email' value=''></p> 
<p><input type='submit' name='submit' value='Submit'></p> 
</form>

Open in new window

0
Comment
Question by:dvointeractive
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
7 Comments
 
LVL 58

Accepted Solution

by:
Julian Hansen earned 1400 total points (awarded by participants)
ID: 41783002
This seems to be a duplicate of this question https://www.experts-exchange.com/questions/28966234/help-modify-this-script-to-send-CSV-file-as-email-attachment-on-form-submit.html

In that question I posted links to PHPMailer which is a code solution to the problem. It is very easy to use and if you scroll down on that link there is a comprehensive example on how to use it.
From that page

1. Include the PHPMailer class
require 'PHPMailerAutoload.php';

Open in new window


2. Create a new instance of PHPMailer
$mail = new PHPMailer;

Open in new window


3. If you need to specify SMTP logon credentials then refer to that page on how to do that - most ISP's you can just do a standard send.

4. Set your sender
$mail->setFrom('from@example.com', 'Mailer');

Open in new window


5. Add your recipients
$mail->addAddress('joe@example.net', 'Joe User');
$mail->addAddress('ellen@example.com');

Open in new window


6. Set your supply to
$mail->addReplyTo('info@example.com', 'Information');

Open in new window


7. Add attachment
$mail->addAttachment('/var/tmp/myfile.csv');

Open in new window


8. If this is an HTML message then set that
$mail->isHTML(true);  

Open in new window


9. Set subject, body and alt body (latter is the text equivalents, useful for getting SPAM score down)
$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

Open in new window


10. Send and error check
if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

Open in new window


It is literally that simple - all you need is in the link I posted in the "Simple Example"
0
 
LVL 58

Assisted Solution

by:Julian Hansen
Julian Hansen earned 1400 total points (awarded by participants)
ID: 41783007
Your CSV is generated as a string - not a file so you need to use AddStringAttachment. I have put some demo code based on your code below. You will need to amend email's etc
I have put the changes between comments including the require - typically require goes to the top of the file so move it after code is working, I put it there so all changes are in one place.
<?php
if(isset($_POST['submit'])){

    //collect form data
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $title = $_POST['title'];
    $phone = $_POST['phone'];
    $fax = $_POST['fax'];
    $email = $_POST['email'];

    //check name is set
    if($firstName ==''){
        $error[] = 'Name is required';
    }

    //check for a valid email address
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
         $error[] = 'Please enter a valid email address';
    }

    //if no errors carry on
    if(!isset($error)){

        # Title of the CSV
        $Content = "firstName, lastName, title, phone, fax, email\n";

        //set the data of the CSV
        $Content .= "$firstName, $lastName, $title, $phone, $fax, $email\n";

        # set the file name and create CSV file
        $FileName = "formdata-".date("d-m-y-h:i:s").".csv";
		
		// ** ADDED MAIL CODE
		// ATTACHMENT FROM STRING INSTEAD OF A FILE
		// require usually goes at the top of the file 
		// I have put it here to group the changes
		
		require 'PHPMailerAutoload.php';
		$mail = new PHPMailer;
		$mail->setFrom('web@dvointeractive.com', 'Mailer');
		$mail->addAddress('someone@somewhere.net', 'Joe User');
		$mail->AddStringAttachment($Content,$FileName);
		$mail->isHTML(true); 
		$mail->Subject = 'Here is the subject';
		$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
		$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
		if(!$mail->send()) {
			echo 'Message could not be sent.';
			echo 'Mailer Error: ' . $mail->ErrorInfo;
		} else {
			echo 'Message has been sent';
		}
		// END ADDITION
		
        header('Content-Type: application/csv'); 
        header('Content-Disposition: attachment; filename="' . $FileName . '"'); 
        echo $Content;
        exit();
    }
}

//if their are errors display them
if(isset($error)){
    foreach($error as $error){
        echo "<p style='color:#ff0000'>$error</p>";
    }
}
?> 

<form action='' method='post'>
<p><label>First Name</label><br><input type='text' name='firstName' value=''></p> 
<p><label>Last Name</label><br><input type='text' name='lastName' value=''></p> 
<p><label>Title</label><br><input type='text' name='title' value=''></p> 
<p><label>Phone</label><br><input type='text' name='phone' value=''></p> 
<p><label>Fax</label><br><input type='text' name='fax' value=''></p> 
<p><label>Email</label><br><input type='text' name='email' value=''></p> 
<p><input type='submit' name='submit' value='Submit'></p> 
</form>

Open in new window

0
 
LVL 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 600 total points (awarded by participants)
ID: 41783256
No points for this please, but this construct seems to be something that a lot of novice PHP programmers keep copying over and over without understanding that it's meaningless drivel with potentially dangerous consequences.  Really.  Please don't do this.
    //collect form data
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $title = $_POST['title'];
    $phone = $_POST['phone'];
    $fax = $_POST['fax'];
    $email = $_POST['email'];

Open in new window

Instead of copying the request variable into $firstName, just use $_POST['firstName'].  That way your colleagues (or you, it it's been more than a few days) can see that you used dangerous and unfiltered external data in your script!

If this sounds to you like there may be something wrong about copying request variables without filtering them, you're on the right track!  Maybe learn about "accept only known good values" (Google the phrase).
0
 
LVL 58

Expert Comment

by:Julian Hansen
ID: 41847885
I think that a couple of comments in this thread addressed the question
1

Featured Post

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question