$ _FILES表格中为空

时间:2017-12-09 18:37:25

标签: php html

我有以下形式将其数据发送到php文件,然后处理数据并通过电子邮件发送给我。问题是我试图将文档与多部分表单一起上传并且它无法正常工作。它只发送没有附件的电子邮件。奇怪的是它曾经工作过,但我不确定我改变了什么。 PHP表单中的$_FILES现在总是空的,这表明我的html而不是PHP存在问题。我已经通过this链接中的可能解决方案,但它们都没有为我工作。任何人都可以看到这种形式的错误吗?

<form id="pre-register-contact-form" action="preregisterform.php" method="post" enctype="multipart/form-data" role="form">
    <div class="messages"></div>
    <div class="controls">
        <div class="form-group">
          <label for="name">Name*</label>
          <input required="required" name="name" type="text" class="form-control" id="name" placeholder="Enter your full name" data-error="Please make sure you've entered your name.">
          <div class="help-block with-errors"></div>
        </div>
        <div class="form-group">
          <label for="age">Age</label>
          <input name="age" type="number" class="form-control" id="age" placeholder="Enter your age">
          <div class="help-block with-errors"></div>
        </div>
      <div class="form-group">
        <label for="email">Email address*</label>
        <input required="required" name="email" type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter your email address" data-error="Please make sure you've entered your email address.">
        <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
        <div class="help-block with-errors"></div>
      </div>
      <div class="form-group">
        <label for="phone">Phone Number</label>
        <input name="phone" type="tel" class="form-control" id="phone" aria-describedby="phoneHelp" placeholder="Enter your phone number">
        <small id="phoneHelp" class="form-text text-muted">We'll never share your phone number with anyone else.</small>
        <div class="help-block with-errors"></div>
      </div>
      <div class="form-group">
        <label for="comments">Comments</label>
        <textarea name="comments" class="form-control" id="comments" placeholder="Add anything extra that you'd like to tell us about yourself here." rows="3"></textarea>
        <div class="help-block with-errors"></div>
      </div>
      <div class="form-group">
        <label for="cv">Upload CV*</label>
        <input required="required" name="cv" type="file" accept=".pdf,.doc,.docx" class="form-control-file" id="cv" data-error="Please make sure you've uploaded a CV.">
        <small id="cvHelp" class="form-text text-muted" aria-describedby="cvHelp">Please make sure it is in PDF or Word format.</small>
        <div class="help-block with-errors"></div>
      </div>
  <div class="form-group">
    <div class="g-recaptcha" data-sitekey="6LcxSDgUAAAAAEM5qhjSDGS-Vu9HJSzLiL7yaAIG"></div>
  </div>
  <input type="submit" class="btn btn-success btn-send" value="Submit">
  </div>
</form>

我的PHP文件如下(删除敏感信息):

<?php
// require ReCaptcha class
require('../elements/recaptcha/recaptcha-master/src/autoload.php');

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

require_once('../elements/mail/PHPMailer.php');
require_once('../elements/mail/Exception.php');
require_once('../elements/mail/SMTP.php');

$mail = new PHPMailer(true);

// configure

$sendTo = 'an_email_address_here';
$subject = 'New Pre-Register Contact Form Email';
$fields = array('name' => 'Name', 'age' => 'Age', 'phone' => 'Phone', 'email' => 'Email', 'comments' => 'Comments', 'cv' => 'CV'); // array variable name => Text to appear in the email
$okMessage = 'Thank you for your message. We will be in touch when the right vacancy for you comes up.';
$errorMessage = 'There was an error submitting the form. Please make sure your details are correct and try again.';
$recaptchaSecret = 'Some_alphanumeric_value_here';

// let's do the sending

try
{
    if (!empty($_POST)) {

        // validate the ReCaptcha, if something is wrong, we throw an Exception, 
        // i.e. code stops executing and goes to catch() block

        if (!isset($_POST['g-recaptcha-response'])) {
            throw new \Exception('ReCaptcha is not set.');
        }

        // do not forget to enter your secret key in the config above 
        // from https://www.google.com/recaptcha/admin

        $recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost());

        // we validate the ReCaptcha field together with the user's IP address

        $response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);


        if (!$response->isSuccess()) {
            throw new \Exception('ReCaptcha was not validated.');
        }

        // everything went well, we can compose the message, as usually




        //Server settings
        //$mail->SMTPDebug = 2;                                 // Enable verbose debug output
        $mail->isSMTP();                                      // Set mailer to use SMTP
        $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
        $mail->SMTPAuth = true;                               // Enable SMTP authentication
        $mail->Username = 'some_email_address_here';                 // SMTP username
        $mail->Password = 'a_password';                           // SMTP password
        $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
        $mail->Port = 465;                                    // TCP port to connect to




        //Recipients
        $mail->setFrom("an_email_address", "Some_Name");
        $mail->addReplyTo($_POST["email"], $_POST["name"]);
        $mail->addAddress('an_email_address', 'some_name');     // Add a recipient

            // This bit is always false
            if (array_key_exists('cv', $_FILES)) {
                $file_type = $_FILES['cv']['type'];
                if (($file_type != 'application/pdf' || $file_type != 'application/msword')) {
                    throw new \Exception("Please make sure you are only uploading a PDF or a Word document.");
                }
                $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['cv']['name']));

                $file_name        = $_FILES['cv']['name'];
                $file_size        = $_FILES['cv']['size'];

                $file_error       = $_FILES['cv']['error'];

                if (move_uploaded_file($_FILES['cv']['tmp_name'], $uploadfile)) {
                    $mail->addAttachment(
                        $uploadfile,
                        $file_name,
                        'base64',
                        $file_type
                    );
                }
            }

            $emailText = "";

            foreach ($_POST as $key => $value) {
                if (isset($fields[$key])) {
                    $emailText .= "<b>$fields[$key]:</b> $value<br>";
                }
            }

            $emailText .= "<br><br><span style=\"font-size: 12px; color: grey;\">Email sent via the careers pre-register contact form.</span><br>";

        //Content
        $mail->isHTML(true);                                  // Set email format to HTML
        $mail->Subject = $subject;
        $mail->Body    = $emailText;
        $mail->AltBody = $emailText;

        $mail->send();
            $responseArray = array('type' => 'success', 'message' => $okMessage);
    }
} catch (Exception $e) {
    $responseArray = array('type' => 'danger', 'message' => $errorMessage);
}

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');

    echo $encoded;
}
else {
    echo $responseArray['message'];
}

修改

记得我在表格中使用AJAX!这是JQuery,我认为这导致了问题:

$('#pre-register-contact-form').on('submit', function (e) {
    if (!e.isDefaultPrevented()) {
        var url = "preregisterform.php";

        $.ajax({
            type: "POST",
            url: url,
            contentType: false,
            data: $(this).serialize(),
            success: function (data)
            {
                var messageAlert = 'alert-' + data.type;
                var messageText = data.message;

                var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
                if (messageAlert && messageText) {
                    $('#pre-register-contact-form').find('.messages').html(alertBox);
                    $('#pre-register-contact-form')[0].reset();
                    grecaptcha.reset();
                }
            }
        });
        return false;
    }
})

1 个答案:

答案 0 :(得分:0)

当您使用ajax上传文件时,您应该像这样使用Formdata:

$('#pre-register-contact-form').on('submit', function (e) {
    var this = $(this);
    if (!e.isDefaultPrevented()) {
        var url = "preregisterform.php";

        $.ajax({
            type: "POST",
            url: url,
            data: new FormData(this),
            dataType:'json',
            processData: false,
            contentType: false,
            success: function (data)
            {
                var messageAlert = 'alert-' + data.type;
                var messageText = data.message;

                var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
                if (messageAlert && messageText) {
                    $('#pre-register-contact-form').find('.messages').html(alertBox);
                    $('#pre-register-contact-form')[0].reset();
                    grecaptcha.reset();
                }
            }
        });
        return false;
    }
})

You can find more detailed information here about how to send/upload files with ajax