简体   繁体   中英

PHP create Form to CSV and Send to email as attachment

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: APSR2020 <2020@coac.co.jp>\r\n";

    /* Prepare autoresponder subject */
$respond_subject = "Sign-up for APSR 2020 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 APSR 2020.

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

Congress Secretariat of APSR 2020
subs-apsr 2020@coac.co.jp

Please keep get in touch with: https://apsr2020.jp
";

/* 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 APSR 2020.</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>

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('you@example.com', 'Your Name'); //Name is optional
$email->Subject   = 'Message Subject';
$email->Body      = $bodytext;
$email->AddAddress( 'destinationaddress@example.com' );

$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';

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

return $email->Send();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM