多上传附件联系表单

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多上传附件联系表单相关的知识,希望对你有一定的参考价值。

作为php的初学者,我试图通过联系表单上传多个文件,最后发送一封包含所有附件和信息的电子邮件。

我已经从头开始联系表单工作,发送一个附件和所有信息到我的电子邮件,甚至添加自动回复发件人电子邮件。

如你所见,我从foreach($_FILES开始编码多重上传,但没有成功。

其余的代码是发送邮件和自动响应。

希望你们能帮助我。谢谢

<form id="contact-form" class="needs-validation" action="careers-post.php" method="POST" role="form" autocomplete="on" enctype="multipart/form-data" novalidate>
<div class="messages">
<?php
if(!empty($_GET['msg'])  && $_GET['msg']=='success'){
    echo '<div class="alert alert-success">Thank you for your submission. We will review your application and contact you with additional information.</div>'; }
else if(!empty($_GET['msg'])  && $_GET['msg']=='fail'){
    echo '<div class="alert alert-danger">Message could not be sent... Please try agai </div>';
    }
?>
</div>
                <div class="form-row mb-3">
                    <div class="col-3 mb-3">
                        <select id="title" name="title" class="form-control" aria-invalid="false" data-error="Select" required>
                            <option hidden disabled selected value>Salutation</option>
                            <option value="Mr.">Mr.</option>
                            <option value="Mrs.">Mrs.</option>
                            <option value="Ms.">Ms.</option>
                        </select>
                        <div class="title-arrow"></div>
                        <div class="help-block with-errors"></div>
                    </div>

                    <div class="col mb-3">
                        <input id="fname" type="text" name="fname" placeholder="First name" class="form-control"
                            data-error="Firstname is required.">
                        <div class="help-block with-errors"></div>
                    </div>
                    <div class="col mb-3">
                        <input id="lname" type="text" name="lname" placeholder="Last name" class="form-control"
                            data-error="Lastname is required.">
                        <div class="help-block with-errors"></div>
                    </div>

                </div>

                <div class="form-row mb-3">
                    <div class="col mb-3">

                        <input type="email" name="email" class="form-control" id="email" placeholder="Email*"
                            pattern="[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,4}$" required>
                        <div class="valid-feedback">Looks good!</div>
                    </div>
                    <div class="col mb-3">

                        <input type="email" name="confirm_email" class="form-control" id="confirm_email"
                            placeholder="Confirm Email*" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,4}$" required>
                        <div id="validate" class="valid-feedback">Emails should match </div>
                    </div>
                </div>

                <div class="form-row mb-3">
                    <div class="col mb-3">
                        <input id="city" type="text" name="city" class="form-control" placeholder="City"
                            data-error=" Please enter your City">
                        <div class="help-block with-errors"></div>
                    </div>
                    <div class="col">
                        <select id="residence" name="residence" class="form-control" aria-invalid="false"
                            data-error="Select Country please" required>
                            <option hidden disabled selected value>Country*</option>
                            <option value="AFG">Afghanistan</option>
                            <option value="ALA">Åland Islands</option>
                            <option value="ALB">Albania</option>
                            <option value="long">List goes on and on</option>
                        </select>
                        <div class="country-arrow"></div>
                        <div class="help-block with-errors"></div>
                    </div>
                </div>

                <div class="form-row mb-3">
                    <div class="col mb-3">
                        <select id="engagement" name="engagement" class="form-control" aria-invalid="false"
                            data-error="Select Country please">
                            <option hidden disabled selected value>Interested to enhance  team by working</option>
                            <option value="Remotely-Part-Time">Remotely - Part time/Project Based</option>
                            <option value="Remotely-Full-Time">Remotely - Full time</option>
                            <option value="On-Premise-Full-Time">On premise - Full time</option>
                            <option value="On-Premise-Part-Time">On premise - Part time/Project Based</option>
                        </select>
                        <div class="interest-arrow"></div>
                        <div class="help-block with-errors"></div>
                    </div>
                </div>

                <div class="form-row mb-3 mt-3">
                    <div class="col">
                        <h5 class="secondary-700 mb-2 text-center">Domain of interests</h5>
                        <div class="row">
                            <div class="col flex-center">
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="checkbox" id="interest" name="interest"
                                        value="Customer-Strategy">
                                    <label class="form-check-label text-dark" for="interest">Data Science</label>
                                </div>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="checkbox" id="interest" name="interest" value="GDPR-Compliance">
                                    <label class="form-check-label text-dark" for="interest">GDPR Compliance</label>
                                </div>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="checkbox" id="interest" name="interest"
                                        value="Personalized-Marketing">
                                    <label class="form-check-label text-dark" for="interest">Personalized Marketing</label>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>

                <div class="form-row">
                    <div class="col mt-3">
                        <textarea id="message" class="form-control" name="message" rows="6"
                            placeholder="Please briefly describe how can you contribute to our success"
                            data-error="Enter your message please."></textarea>
                        <div class="help-block with-errors"></div>
                    </div>
                </div>
                <div class="form-row align-items-center mt-5">
                    <div class="col flex-end">
                        <label for="attachment">
                            <h5 class="secondary-700" style="margin-bottom: 0 !important;">Attach your resume</h5>
                        </label>
                    </div>
                    <div class="col">
                        <input type="file" id="attachment" name="attachment" style="border: 0 !important;">
                    </div>

                </div>
                <div class="row align-items-center mt-4">
                    <div class="col text-center">
                        <input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
                        <label class="form-check-label" for="invalidCheck">
                            <h6 class="secondary-700 ml-3">I have read and agree to the terms<br>of <a class="text-primary"
                                    href="privacy.html">Privacy Notice</a></h6>
                        </label>
                        <div class="invalid-feedback">
                            You must agree before submitting.
                        </div>
                    </div>
                </div>
                <div class="form-row justify-content-center">
                    <div class="col-auto">
                        <input type="submit" id="message" class="btn btn-careers" value="Send Message">
                    </div>
                </div>
            </form>
<?php

use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;

require 'vendor/phpmailer/phpmailer/src/Exception.php';
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/phpmailer/src/SMTP.php';

$mail = new PHPMailer(true);

$target_dir = "uploads/";

$target_file = $target_dir . basename($_FILES["attachment"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
if (file_exists($target_file)) {
    $uploadOk = 0; }
if ($_FILES["attachment"]["size"] > 10000000) {
    $uploadOk = 0; }
if (
    $imageFileType != "pdf" && $imageFileType != "txt" && $imageFileType != "docx"
    && $imageFileType != "jpg"
) { $uploadOk = 0; }
if ($uploadOk == 0) {
} else {
    if (move_uploaded_file($_FILES["attachment"]["tmp_name"], $target_file)) {
    } else {
    }
}

$from = 'Careers contact<info@email.me>';
$sendTo = 'careers@email.me';
$subject = 'New message from Careers form';
$fields = array(
    'title' => 'Salutation',
    'fname' => 'Firstname',
    'lname' => 'Lastname',
    'email' => 'Email',
    'city' => 'City',
    'residence' => 'Country',
    'engagement' => 'Interested',
    'interest' => 'Domain interest',
    'message' => 'Message'
);
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';

error_reporting(E_ALL & ~E_NOTICE);

try {
    $mail->SMTPDebug = 0;
    $mail->isSMTP();
    $mail->Host       = 'mail.email.me';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'info@email.me';
    $mail->Password   = '5rySCfGKoI7cmGu!';
    $mail->SMTPSecure = '';
    $mail->Port       = 587;
    $mail->setFrom('info@email.me', 'Careers');
    $mail->addAddress('careers@email.me', 'Careers');
    $mail->addReplyTo('careers@email.me', 'Careers');
    $mail->addAttachment($target_file);
    $emailText = "You have a new message from your Careers form
=============================
";
    foreach ($_POST as $key => $value) {
        if (isset($fields[$key])) {
            $emailText .= "$fields[$key]: $value
";
        }
    }
    $emailTextHtml = "<h2>You have a new message from your Careers form</h2><hr>";
    $emailTextHtml .= "<table>";
    foreach ($_POST as $key => $value) {
        if (isset($fields[$key])) {
            $emailTextHtml .= "<tr><th>$fields[$key]</th><td>$value</td></tr>";
        }
    }
    $emailTextHtml .= "</table><hr>";
    $emailTextHtml .= "<p>Have a nice day";
    $mail->isHTML(true);
    $mail->Subject = 'Contact Information ';
    $mail->Body    = $emailTextHtml;
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    $mail->send();

    $newMail = new PHPMailer(true);
    $newMail->SMTPDebug = 0;
    $newMail->isSMTP();
    $newMail->Host       = 'mail.email.me';
    $newMail->SMTPAuth   = true;
    $newMail->Username   = 'info@email.me';
    $newMail->Password   = '5rySCfGKoI7cmGu!';
    $newMail->SMTPSecure = '';
    $newMail->Port       = 587;
    $newMail->setFrom('info@email.me', 'Careers');
    $newMail->addAddress($_POST['email'], $_POST['fname'] . ' ' . $_POST['lname']);

    $emailBody = file_get_contents('careersbody.php');
    $emailBody = str_replace('%firstname%', $_POST['fname'], $emailBody);
    $emailBody = str_replace('%user_mail%', $_POST['email'], $emailBody);
    $newMail->isHTML(true);
    $newMail->Subject = 'Application Confirmation';
    $newMail->Body    = $emailBody;
    $newMail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    if ($newMail->send()) {
        header('Location: careers.php?msg=success&ex=y');
    } else {
        header('Location: careers.php?msg=fail');
    }
    } catch (Exception $e) {
        header('Location: careers.php?msg=fail');
    }
die;
答案

未经测试但也许这可能有所帮助。

设置文件输入以接受多个文件

<form id='contact-form' class='needs-validation' action='careers-post.php' method='POST' role='form' autocomplete='on' enctype='multipart/form-data' novalidate>
    <div class='col'>
        <input type='file' name='attachment[]' multiple>
    </div>
    <!-- assumed to have additional fields -->
    <!--
        <label for="title">Salutation<input type="text" name="title" value="" /></label>
        <label for="fname">Firstname<input type="text" name="fname" value="" /></label>
        <label for="lname">Lastname<input type="text" name="lname" value="" /></label>
        <label for="email">Email<input type="text" name="email" value="" /></label>
        <label for="city">City<input type="text" name="city" value="" /></label>
        <label for="residence">Country<input type="text" name="residence" value="" /></label>
        <label for="engagement">Interested<input type="text" name="engagement" value="" /></label>
        <label for="interest">Domain interest<input type="text" name="interest" value="" /></label>
        <label for="message">Message<input type="text" name="message" value="" /></label>
    -->
    <input type='submit' />
</form>

表单操作/邮件处理程序

<?php

    $field='attachment';
    $target_dir = "uploads/";
    $errors=array();
    $allowed=['pdf','txt','docx','jpg'];
    $attachments=[];

    $okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
    $errorMessage = 'There was an error while submitting the form. Please try again later';


    foreach( $_FILES[ $field ]['name'] as $i => $name ) {
        try{
            if( !empty( $_FILES[ $field ]['tmp_name'][$i] ) ) {
                $name = $_FILES[ $field ]['name'][$i];
                $size = $_FILES[ $field ]['size'][$i];
                $type = $_FILES[ $field ]['type'][$i];
                $tmp  = $_FILES[ $field ]['tmp_name'][$i];
                $error= $_FILES[ $field ]['error'][$i];
                $ext  = strtolower( pathinfo( $name, PATHINFO_EXTENSION ) );

                $uploadOk = true;

                if( $error == UPLOAD_ERR_OK && is_uploaded_file( $tmp ) ){
                    $target_file = $target_dir . $name;

                    if( file_exists( $target_file ) ) $uploadOk=false;
                    if( $size > 10000000 ) $uploadOk=false;
                    if( !in_array( $ext, $allowed ) ) $uploadOk=false;

                    if( $uploadOk ){
                        $status = move_uploaded_file( $tmp, $target_file );
                        if( $status ){
                            $attachments[]=$target_file;
                        } else {
                            throw new Exception(sprintf('unable to save %s',$name));
                        }
                    } else {
                        throw new Exception( sprintf('problem with %s',$name) );
                    }
                }
            }
        }catch( Exception $e ){
            $errors[]=$e->getMessage();
        }
    }

    if( empty( $errors ) ){

        use PHPMailerPHPMailerPHPMailer;
        use PHPMailerPHPMailerException;
        require 'vendor/phpmailer/phpmailer/src/Exception.php';
        require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
        require 'vendor/phpmailer/phpmailer/src/SMTP.php';
        $mail = new PHPMailer( true );

        $from = 'Careers <email@email.se>';
        $sendTo = 'email@email.se';
        $subject = 'New message from Careers form';


        $mail->AddAddress( $sendTo );
        $mail->Subject( $subject );
        $mail->SetFrom( $from );
        $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';


        $fields = array(
            'title' => 'Salutation',
            'fname' => 'Firstname',
            'lname' => 'Lastname',
            'email' => 'Email',
            'city' => 'City',
            'residence' => 'Country',
            'engagement' => 'Interested',
            'interest' => 'Domain interest',
            'message' => 'Message'
        );

        $html=array();
        foreach( $fields as $field => $text ){
            if( !empty( $_POST[ $field ] ) ) $html[]=sprintf( '<div>%s: %s</div>', $text, filter_input( INPUT_POT, $field, FILTER_SANITIZE_STRING ) );
        }

        /* add message body */
        if( !empty( $html ) ){
            $mail->MsgHTML( implode( PHP_EOL, $html ) );
        }

        /* add attachments */
        foreach( $attachments as $file ){
            $mail->AddAttachment( $file );
        }

        $status = $mail->send();
        exit( $status ? $okMessage : $errorMessage );
    }
?>

我从未使用过PHPMailer,但我发现了一个例子here用于发送附件。

据推测应该有其他形式字段,可能命名为数组$fields中的键???我想这是添加到邮件正文中

以上是关于多上传附件联系表单的主要内容,如果未能解决你的问题,请参考以下文章

php 表单自定义表单文件上传附件多附件表单

通过jQuery Ajax提交表单数据时同时上传附件

电子邮件表单根据附件发送多封邮件

使用微搭低代码实现附件上传

使用微搭低代码实现附件上传

如何在某个网页上自动填写表单并上传附件,并提交。页面上用的是type = file这个东西