I have the following form which sends its data to a php file which then processes the data and emails it to me. The problem is that I'm trying to upload a document along with the multipart form and it's not working. It sends the email just without the attachment. The weird thing is it used to work, but I'm not sure what I changed. $_FILES
in the PHP form is always empty now, which suggests a problem with my html and not the PHP. I have been through the possible solutions in this link, but none of them worked for me. Can anyone see what's wrong with this form?
<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>
My PHP file is as follows (sensitive info removed):
<?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'];
}
EDIT
Just remembered I am using AJAX with the form! Here is the JQuery, I think this is causing the problem:
$('#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">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#pre-register-contact-form').find('.messages').html(alertBox);
$('#pre-register-contact-form')[0].reset();
grecaptcha.reset();
}
}
});
return false;
}
})