1

I am creating a webpage that has a form, and in that form I need to save it as csv and I need it to be sent to an email as an attachment file, how do I do that?

First how can I output all of the inputs to csv, then save it as csv file and automatically attach it to email.

Below is the code I've tried :

PHP

<?php

    // define variables and set to empty values
$nameErr = $emailErr = $countryErr = $confirmErr = "";

function clean_text($string)
{
 $string = trim($string);
 $string = stripslashes($string);
 $string = htmlspecialchars($string);
 return $string;
}

if(isset($_POST['email'])) {
 
    // EDIT THE 2 LINES BELOW AS REQUIRED
    $email_to = "sample@email";
    $email_subject = "Form Submission";

    function died($error) {
        // your error code can go here
        echo "We are very sorry, but there were error(s) found with the form you submitted. ";
        echo "These errors appear below.<br /><br />";
        echo $error."<br /><br />";
        echo "Please go back and fix these errors.<br /><br />";
        exit();
    }
 
    // validation expected data exists
    if(!isset($_POST['name']) ||
        !isset($_POST['email']) ||
        !isset($_POST['country']) ||
        !isset($_POST['confirm_email'])) {
        died('We are sorry, but there appears to be a problem with the form you submitted.');       
    }
 
    $name = $_POST['name']; // required
    $email_from = $_POST['email']; // required
    $country = $_POST['country']; // not required
    $confirm_email = $_POST['confirm_email']; // required
 
    $error_message = "";
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
 
  if(!preg_match($email_exp,$email_from)) {
    $error_message .= 'The Email Address you entered does not appear to be valid.<br />';
  } 
 
    $string_exp = "/^[A-Za-z .'-]+$/";
 
  if(!preg_match($string_exp,$name)) {
    $error_message .= 'The Name you entered does not appear to be valid.<br />';
  }
    
      if(strlen($error_message) > 0) {
    died($error_message);
  }
    
    $email_message = "Subsciber Details Information.\n\n";
     
    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }

    $email_message .= "Full Name: ".clean_string($name)."\n";
    $email_message .= "Country: ".clean_string($country)."\n";
    $email_message .= "Email: ".clean_string($email_from)."\n";
    $email_message .= "Confirmed Email: ".clean_string($confirm_email)."\n";
 
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);  
    
    /*Autoreply Sender Name*/
 $headerss = "FROM: Comapny name <[email protected]>\r\n";
    
    /* Prepare autoresponder subject */
$respond_subject = "Sign-up for CompanyName Mailing List Completed";
    
/* Prepare autoresponder message */
$respond_message = "Thank you for your interest in sign-up for our mailing list.
We will keep you updated on CompanyName.

In the case that this email is unexpected, it will be troubling, but please inquire through the given address.

Congress Secretariat of CompanyName
subs-apsr [email protected]

";
    
/* Send the response message using mail() function */

mail($email_from, $respond_subject, $respond_message, $headerss);
//redirect to the 'thank you' page
header('Location: thank-you-page.html');
    
?>
<!-- include your own success html here -->
<?php
}
?>

HTML form

<form name="contactform" method="post">
                <div class="keep__me__posted">

                    <p>Please sign up NOW.</p>
                    <p class="margin__p">We will keep you updated on CompanyName</p>

                    <div class="input__form">
                        <label for="name">Name</label>
                        <input type="text" id="name" name="name" maxlength="50" size="30" value="" required>
                    </div>
                    <div class="input__form">
                        <label for="country">Country</label>
                        <input type="text" id="country" name="country" maxlength="30" size="30" value="" required>
                    </div>
                    <div class="input__form">
                        <label for="email">Email Address</label>
                        <input type="email" id="email" name="email" maxlength="80" size="30" value="" required>
                    </div>
                    <div class="input__form">
                        <label for="confirm_email">Confirm Email</label>
                        <input type="email" id="confirm_email" name="confirm_email" maxlength="30" size="30" required>
                    </div>
                    <div class="input__form submit">
                        <tr>
                            <td colspan="2" style="text-align:center">
                                <input type="submit" value="Subscribe" class="submit" onclick="checkEmail()">
                            </td>
                        </tr>
                    </div>
                </div>
            </form>
6
  • and what problem are you having with this code, specifically? Commented Nov 6, 2018 at 9:47
  • CSV is about storing "table-like" data as text. You have a single form with a fistful of fields. Are you sure about CSV? Or, perhaps, do you want to append the result to an existing CSV? Commented Nov 6, 2018 at 9:48
  • I am asking for a help. @ADyson Commented Nov 6, 2018 at 9:59
  • @tevemadar yes it should be csv file. whenver I input a data to the form, it will output as csv file and it should be attached to the email Commented Nov 6, 2018 at 10:00
  • help with what, specifically? There's a lot of code here...which part of it is giving you a problem? Please explain any errors and/or unexpected behaviour you're seeing. You've told us what you want the code to do, but not what it does now. Don't expect people to spend their time to work it out, when you can just tell us. Thanks. Commented Nov 6, 2018 at 10:05

1 Answer 1

6

To write in your csv file, you can take a look at this function :

$file = fopen('yourFile.csv', 'w');
fputcsv($file, array('this','is some', 'csv "stuff", you know.'));
fclose($file);

To send this file with the mail, I think the easier option is to use PHPMailer. Don't really know how to use it, but you can easily find it out here. You firstly need to download and instal the package found on gitHub and then use it like this :

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$email = new PHPMailer();
$email->SetFrom('[email protected]', 'Your Name'); //Name is optional
$email->Subject   = 'Message Subject';
$email->Body      = $bodytext;
$email->AddAddress( '[email protected]' );

$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';

$email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );

return $email->Send();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.