php sends blank e-mail - javascript

For some reason we recieve around 5/10 emails a day from the support page that are empty, no input fields filled in but also no input fields fetched at all. The emails only show the subject.
If we test the form it works fine and the e-mail shows the info we filled and even if we fill in nothing we still recieve an e-mail stating the input field names. In the recordings the website makes of the users on the support page, there doesn't seem te be a user filling in the form at the time we recieve a 'blank' email.
I would some help because i'm completely lost on how to fix this.
Javascript:
$( document ).ready(function() {
var $form = $('form');
$form.submit(function() {
$.post($(this).attr('action'), $(this).serialize(), function(response) {
$('.email-popup-container').css({
"transform": "scale(.9)",
});
setTimeout(function(){
$('.email-popup-container').animate({
"margin-left": "+=1200px",
"opacity": "0",
}, 400, function(){
setTimeout(function(){
$('#email-popup').removeClass('is-visible').ready(function(){
$('.email-popup-container').css({
"transform": "scale(1)",
});
$('#contact-form')[0].reset();
$('.email-popup-container').animate({
"margin-left": "-=1200px",
}, 0
);
});
},150)
setTimeout(function(){
$.notify(" Thank you! We have recieved your e-mail.", {
delay: 4000,
color: "#fff",
background: "#1AC16D",
type: "success",
icon: "check",
align: "right",
animationType: "fade"
});
},400)
});
},600)
}, 'json');
return false;
});
});
php:
// configure
$from = 'New Message - Support Page <istillwebsite#donotreply.com>';
$sendTo = 'New Message - Support Page <sales#istillmail.com>';
$subject = 'Message from iStill Support Page';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email
$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';
// let's do the sending
try
{
$emailText = "Someone sent a message from the support page\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($sendTo, $subject, $emailText, "From: " . $from);
$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'];
}
?>

This is a super unsafe way to send mails. Someone can just call your .php script and send multiple mails. So it is probably a bot or something like this, that is calling your script.
To prevent this, you can use Google reCaptcha for example.

Related

How to use ajax for login form

I am currently creating a login form in PHP PDO and I am using ajax to display the relevant messages on screen, e.g.
"Logging in..."
"Some input fields are empty"
"Your username is required"
"Your password is required"
Validation such as checking if input fields are empty is working fine along with when login credentials appear to be incorrect however when I login with correct credentials I just get message "Logging in..." and nothing happens, I don't even think it sets the session. I have also added a token to prevent CSRF and was just wondering if i'm using it correctly.
I'm unsure of what is causing my code not to proceed with logging in.
my ajax script:
<script type='text/javascript'>
$(document).ready(function () {
var submitButton = $("#btn-login");
submitButton.on('click', function (e) {
e.preventDefault();
// Get input field values of the contact form
var loginFormInputs = $('#login-form :input'),
userName = $('#txt_uname_email').val(),
userPassword = $('#txt_password').val(),
token = $('#token').val(),
alertMessage = $('#login-alert-message');
// Disable Inputs and display a loading message
alertMessage.html('<p style="opacity: 1"><i class="fa fa-spinner fa-spin text-success"></i> Logging in..</p>');
submitButton.html('<i class="fas fa-spinner fa-spin"></i>');
loginFormInputs.prop("disabled", true);
// Data to be sent to server
var post_data = {
'form': 'loginForm',
'userName': userName,
'userPassword': userPassword,
'token': token
};
// Ajax post data to server
$.post('./api', post_data, function (response) {
// Load jsn data from server and output message
if (response.type === 'error') {
alertMessage.html('<p><i class="fa-lg far fa-times-circle text-danger"></i> ' + response.text + '</p>');
submitButton.html('Login');
loginFormInputs.prop("disabled", false);
} else {
alertMessage.html('<p><i class="fa-lg far fa-check-circle text-success"></i> ' + response.text + '</p>');
submitButton.html('Login');
window.location = "dashboard";
}
}, 'json');
});
});
</script>
My login function (class.user.php) which is used in api.php:
public function doLogin($uname,$umail,$upass)
{
try
{
$stmt = $this->conn->prepare("SELECT * FROM `settings` LIMIT 1");
$stmt->execute();
$mainten=$stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $this->conn->prepare("SELECT user_id, user_name, user_email, user_pass, status FROM users WHERE user_name=:uname OR user_email=:umail ");
$stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if(password_verify($upass, $userRow['user_pass']))
{
session_regenerate_id(false);
return ["correctPass"=>true, "banned"=> ($userRow['status']== 1) ? true : false, "maintenance"=> ($mainten["maintenance"]== 1) ? true : false];
}
else
{
return ["correctPass"=>false];
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
api.php:
//include class.user.php here and set $login = new USER();
//set $uname, $umail, $upass, $token vars here
if( $_POST && $_POST["form"] === 'loginForm' ) {
// Use PHP To Detect An Ajax Request code is here
// Checking if the $_POST vars well provided, Exit if there is one missing code is here
// PHP validation for the fields required code is here
$validation = $login->doLogin($uname,$umail,$upass);
if($validation["correctPass"]){
if($validation["maintenance"]){
if (!in_array($uname, array('admin'))){
$output = json_encode(
array(
'type' => 'error',
'text' => 'Website under maintenance.'
));
die($output);
}
}
if($validation["banned"]){
$output = json_encode(
array(
'type' => 'error',
'text' => 'User has been banned.'
));
die($output);
}else{
if(Token::check($_POST['token'])) {
$stmtt = $login->runQuery("SELECT user_id FROM users WHERE user_name=:uname OR user_email=:umail ");
$stmtt->execute(array(':uname'=>$uname, ':umail'=>$umail));
$userRow=$stmtt->fetch(PDO::FETCH_ASSOC);
$_SESSION['user_session'] = $userRow['user_id'];
$output = json_encode(
array(
'type' => 'message',
'text' => 'Logged in successfully.'
));
die($output);
//$success = "Logged in successfully, redirecting..";
//header( "refresh:3;url=ab" );
//$login->redirect('dashboard');
} else {
$output = json_encode(
array(
'type' => 'error',
'text' => 'Unexpected error occured.'
));
die($output);
}
}
}
else{
$output = json_encode(
array(
'type' => 'error',
'text' => 'Incorrect username or password.'
));
die($output);
}
}

Why does my submit button gets re-enabled before all fields are filled in?

I'm using the code below to validate (through bootstrap-validator) the content of each field in my contact form (there's also an extra check via google recaptcha). You can see and test the form at at this address.
By default, the submit button is disabled <button id="submit-btn" class="btn-upper btn-yellow btn" name="submit" type="submit" disabled><i class="fa fa-paper-plane-o" aria-hidden="true"></i> SEND</button>, and is supposed to be re-enabled once all the fields are validated via bootstrap-validator and google recaptcha completed.
Issue: the submit button gets re-enabled directly once the first field is filled-in so there must be something somewhere that reactivates it (you can do a test by typing your name in the first field and then put your mouse over the submit button, and you will see that the button is active instead of disabled)
Any idea what the issue is and how to fix this?
Many thanks
JS:
$(document).ready(function() {
$('#contact_form').bootstrapValidator({
feedbackIcons: {
valid: 'fa fa-check',
invalid: 'fa fa-times',
validating: 'fa fa-refresh'
},
fields: {
first_name: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: 'aaVeuillez indiquer votre prénom'
}
}
},
last_name: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: 'aaVeuillez indiquer votre nom'
}
}
},
email: {
validators: {
notEmpty: {
message: 'aaVeuillez indiquer votre adresse e-mail'
},
regexp: {
regexp: '^[^#\\s]+#([^#\\s]+\\.)+[^#\\s]+$',
message: 'aaVeuillez indiquer une adresse e-mail valide'
}
}
},
message: {
validators: {
stringLength: {
min: 20,
max: 1000,
message:'aaVotre message doit faire plus de 20 caractères et moins de 1000.'
},
notEmpty: {
message: 'aaVeuillez indiquer votre message'
}
}
}
}}).on('success.form.bv', function (e) {
e.preventDefault();
$('button[name="submit"]').hide();
var bv = $(this).data('bootstrapValidator');
// Use Ajax to submit form data
$.post($(this).attr('action'), $(this).serialize(), function (result) {
if (result.status == 1) {
$('#error_message').hide();
$('.g-recaptcha').hide();
$('#success_message').slideDown({
opacity: "show"
}, "slow");
$('#contact_form').data('bootstrapValidator').resetForm()
} else {
$('button[name="submit"]').show();
$('#error_message').slideDown({
opacity: "show"
}, "slow")
}
}, 'json');
}
);
});
Submit btn:
<button id="submit-btn" class="btn-upper btn-yellow btn" name="submit" type="submit" disabled><i class="fa fa-paper-plane-o" aria-hidden="true"></i> ENVOYER</button>
Additional script on the contact page:
<script type="text/javascript">
function recaptcha_callback(){
$('#submit-btn').removeAttr('disabled');
}
</script>
my sendmessage.php:
<?php
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->CharSet = 'utf-8';
$email_vars = array(
'message' => str_replace("\r\n", '<br />', $_POST['message']),
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'phone' => $_POST['phone'],
'email' => $_POST['email'],
'organisation' => $_POST['organisation'],
'server' => $_SERVER['HTTP_REFERER'],
'agent' => $_SERVER ['HTTP_USER_AGENT'],
);
// CAPTCHA
function isValid()
{
try {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = ['secret' => '6LtQ6_y',
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return json_decode($result)->success;
}
catch (Exception $e) {
return null;
}
}
// RE-VALIDATION (first level done via bootsrap validator js)
function died($error) {
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 />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['message'])) {
died('*** Fields not filled-in ***');
}
//Enable SMTP debugging.
$mail->SMTPDebug = false;
//Set PHPMailer to use SMTP.
$mail->isSMTP();
//Set SMTP host name
$mail->Host = "smtp.sendgrid.net";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
//Provide username and password
$mail->Username = "fdsfs";
$mail->Password = "#pz7HQ";
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "tls";
//Set TCP port to connect to
$mail->Port = 587;
$mail->FromName = $_POST['first_name'] . " " . $_POST['last_name'];
//To be anti-spam compliant
/* $mail->From = $_POST['email']; */
$mail->From = ('ghdsfds#gmail.com');
$mail->addReplyTo($_POST['email']);
$mail->addAddress("ghdsfds#outlook.com");
//CC and BCC
$mail->addCC("");
$mail->addBCC("");
$mail->isHTML(true);
$mail->Subject = "Nouveau message depuis XYZ";
$body = file_get_contents('emailtemplate.phtml');
if(isset($email_vars)){
foreach($email_vars as $k=>$v){
$body = str_replace('{'.strtoupper($k).'}', $v, $body);
}
}
$mail->MsgHTML($body);
$response = array();
if(isValid()) {
// send mail
if(!$mail->send()) {
$response = array('message'=>"Mailer Error: " . $mail->ErrorInfo, 'status'=> 0);
} else {
$response = array('message'=>"Message has been sent successfully", 'status'=> 1);
}
} else {
// handle error
$response = array('message' => 'Captcha was not valid');
}
/* send content type header */
header('Content-Type: application/json');
/* send response as json */
echo json_encode($response);
?>
Actually your code is working as expected and no error in your code. But in bootstrapValidator you need to check the status of every field before success.form.bv event, like describe below.
Please add this event before .success.form.bv event like describe below.
.on('status.field.bv', function(e, data) {
var $this = $(this);
var formIsValid = true;
$('.form-group', $this).each(function() {
formIsValid = formIsValid && $(this).hasClass('has-success');
});
$('#submit-btn', $this).attr('disabled', !formIsValid);
}).on('success.form.bv', function(e, data) {
Let me know if it not works.
Below is a pseudo code, kinda clone of the page that you shared, with the basic validation checks that are triggered on multiple events (keyup, change, keypress, blur).
It checks if all fields are filled or not, if any one is empty, button won't be enabled.
It checks if the input fields have minimum 2 characters.
It checks if the message field has message length between 20 to 1000.
And in the same manner, we can keep adding custom validations to our needs.
required = function(fields) {
console.clear();
var valid = true;
fields.each(function() { // iterate all
var $this = $(this);
if ((($this.is(':text') || $this.is('textarea')) && !$this.val())) {
valid = false;
}
if ($this.is(":text") && $this.val().length < 3) {
console.log('less than 2 characters..');
valid = false;
}
if ($(this).attr('id') == 'your_message' && ($this.val().length < 20 || $this.val().length > 1000)) {
console.log('aaVotre message doit faire plus de 20 caractères et moins de 1000.');
valid = false;
}
});
return valid;
}
validateRealTime = function() {
var fields = $("form :input");
fields.on('keyup change keypress blur', function() {
if (required(fields)) {
{
$("#register").prop('disabled', false);
}
} else {
{
$("#register").prop('disabled', true);
}
}
});
}
validateRealTime();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
First name<br />
<input type="text" id="user_input" name="firstname" /><br /> Name
<br />
<input type="name" id="name_input" name="name" /><br /> Email<br />
<input type="email" id="email_input" name="email" /><br />
<br/> Your Message
<textarea name="your_message" id="your_message"></textarea>
<br>
<input type="submit" id="register" value="Submit" disabled="disabled" />
</form>
Hope this helps you. Happy Coding!
There seems to be a problem with naming the submit button submit http://bootstrapvalidator.votintsev.ru/getting-started/#name-conflict It might have caused the unexpected behavior
Just write a separated validation to your form
$("#contact_form").on('change', function () {
$("form").each(function(){
if ($(this).find(':input').val()== "")
$('#submit-btn').addClass('disabled');
});
})

Cannot get jquery.multiple.select.js to validate and pass to php the boxes checked

I am using jquery.multiple.select.js v1.1.0 and cannot get this to validate and pass the output to my php mailer. My objective is for the visitor to my site to select from multiple options requesting a quote. So far, I'm able to receive the email with all other fields validated but in the email, I receive"quote for: array" but no selections. Also related, I'm not getting the success or error message on the page even though the email is going out. Can anyone steer me in the right direction? I'll include the page in question here, http://cptest.info/h2contact375.html
here's the validation js
var Contact = {
initialized: false,
initialize: function() {
if (this.initialized) return;
this.initialized = true;
this.build();
this.events();
},
build: function() {
this.validations();
},
events: function() {
},
validations: function() {
$("#contactForm").validate({
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "js/contact-form.php",
data: {
"name": $("#contactForm #name").val(),
"email": $("#contactForm #email").val(),
"telephone": $("#contactForm #telephone").val(),
"message": $("#contactForm #message").val(),
"ms": $("#contactForm #ms").val()
},
dataType: "json",
success: function (data) {
if (data.response == "success") {
$("#contactSuccess").removeClass("hidden");
$("#contactError").addClass("hidden");
$("#contactForm #name, #contactForm #email, #contactForm #telephone, #contactForm #message, #contactForm #ms")
.val("")
.blur()
.closest(".control-group")
.removeClass("success")
.removeClass("error");
if(($("#contactSuccess").position().top - 80) < $(window).scrollTop()){
$("html, body").animate({
scrollTop: $("#contactSuccess").offset().top - 80
}, 300);
}
} else {
$("#contactError").removeClass("hidden");
$("#contactSuccess").addClass("hidden");
if(($("#contactError").position().top - 80) < $(window).scrollTop()){
$("html, body").animate({
scrollTop: $("#contactError").offset().top - 80
}, 300);
}
}
}
});
},
rules: {
name: {
required: true
},
email: {
required: true,
email: true
},
telephone: {
required: true
},
message: {
required: true
},
ms:{
required: true,
message: 'Please select at least one'
},
},
highlight: function (element) {
$(element)
.closest(".control-group")
.removeClass("success")
.addClass("error");
},
success: function (element) {
$(element)
.closest(".control-group")
.removeClass("error")
.addClass("success");
}
});
}
};
Contact.initialize();
here's the php
<?php
// check if fields passed are empty
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message'])||
empty($_POST['telephone'])||
empty($_POST['ms']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!"; return false;
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
$telephone = $_POST['telephone'];
$ms = $_POST['ms'];
// create email body and send it
$to = "myemail#gmail.com";
// put your email
$email_subject = "Contact form submitted by: $name"; $email_body = "You have received a new message. \n\n".
" Here are the details:\n \nName: $name \n ".
"Telephone: $telephone \n" .
"Quote For: $ms \n" .
"Email: $email_address\n Message: \n $message";
//$headers = "From: me#youremail.com\n";
//$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers); return true;
?>
give name to your field called ms otherwise it will not go to php because it identifies name not id and based on your condition checking it will always show No arguments Provided!.
<select id="ms" multiple="multiple" name="ms">
Try Using $_REQUEST in your PHP if $_POST is not providing the data to check.
NOTE: there is no styling added just expect it to send data to your php nothing else.
<?php
// check if fields passed are empty
print_r($_REQUEST);//it should display the send data
//rest of the code with request
DEMO
You can use the following code to validate so validation plugin will not ignore the hidden <select> element.
The magic happens in this line:
ignore: ':hidden:not("#ms")',
add it to validation script
//AjaxCall Code
},
ignore: ':hidden:not("#ms")',
rules: {
//Rules and messages onwards
Above will fix the issue of validation,
And about data not posting, there is no name="" in <select> tag so add it one, and after validation, <select> value will be posted along with other inputs in <form>
<select style="display: none;" name="ms" id="ms" multiple="multiple" >

Stripe AJAX PHP and JavaScript

The below is my code I'm using for my Stripe Subscription Payments, because the site I'm implementing this into is AngularJS I want to keep the site from Refreshing so I'm opting for this AJAX option.
I have commented out a piece of the PHP which is
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => $amount,
'currency' => 'gbp'
));
If I exclude this, the payment goes through once and I'm unsure how this application is able to process the charge if there is no call for it in the PHP file.
If I include the above snippet then the charge goes through twice.
My config.php only has require_once('Stripe.php'); along with my API keys.
So I'm hoping someone could explain why the charge goes through without the charge code piece in there if my code is actually okay for me to continue with.
HTML
<button id="proBtn">Subscribe</button>
JavaScript
Stripe.setPublishableKey('HIDDEN');
$('#proBtn').click(function(){
var token = function(res){
var $input = $('<input type="hidden" name="stripeToken" />').val(res.id);
var tokenId = $input.val();
var email = res.email;
setTimeout(function(){
$.ajax({
url:'/assets/lib/charge.php',
cache: false,
data:{ stripeEmail : email, stripeToken:tokenId, stripePlan: 'pro' },
type:'POST'
})
.done(function(data){
// If Payment Success
console.log(data);
$('#proBtn').html('Thank You').addClass('disabled');
})
.error(function(){
$('#proBtn').html('Error, Unable to Process Payment').addClass('disabled');
});
},500);
//$('form:first-child').append($input).submit();
};
StripeCheckout.open({
key: 'HIDDEN', // Your Key
address: false,
amount: 500,
currency: 'gbp',
name: 'Pro Account',
description: '',
panelLabel: 'Checkout',
allowRememberMe: false,
token: token
});
return false;
});
charge.php
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/assets/lib/config.php');
$token = $_POST['stripeToken'];
$email = $_POST['stripeEmail'];
$plan = $_POST['stripePlan'];
if ( $plan == 'pro' ) {
$amount = 500;
$amountFormat = number_format( $amount / 100, 2) ;
$plan = 'pro';
}
if ( $plan == 'team' ) {
$amount = 2000;
$amountFormat = number_format( $amount / 100, 2) ;
$plan = 'team';
}
Stripe_Plan::retrieve("pro");
Stripe_Plan::retrieve("team");
$customer = Stripe_Customer::create(array(
'email' => $email,
'card' => $token,
'plan' => $plan
));
try {
/*
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => $amount,
'currency' => 'gbp'
));*/
echo 'success';
} catch(Stripe_CardError $e) {
echo "The card has been declined";
echo $token;
}
print_r($token);
echo '<br/>';
print_r($email);
echo '<br/>';
echo $customer->id;
echo '<h1>Successfully charged '.$amountFormat.'!</h1>';
?>
When you create a customer in Stripe it automatically charges them if you pass in a plan. You're basically saying create this customer and sign them up for this plan. That's why you are charging them twice.
Here's a link to the Customer API:
https://stripe.com/docs/api#create_customer

Attaching and Sending files with PHPMailer

I need to make a form on my website that allows users to upload and send files. The form has 3 fields, Name, Email and Attachment.
I need all these 3 fields to be sent to me with the file attached to my email once the user clicks Send.
I have 3 files, the HTML file containing the form:
<div class="span6 control-group">
<label>File Upload:</label>
<input type="file" name="file_upload" id="file_upload" />
</div>
A .js file containing some visual effects for when the file is sent, if there is an error, required fields
var Contact = {
initialized: false,
initialize: function() {
if (this.initialized) return;
this.initialized = true;
this.build();
this.events();
},
build: function() {
this.validations();
},
events: function() {
},
validations: function() {
$("#contactForm").validate({
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "php/upload-form.php",
data: {
"name": $("#contactForm #name").val(),
"email": $("#contactForm #email").val(),
"quote": $("#contactForm #upload_file").val()
}, // Rest is visual effects, then ends with //
Contact.initialize();
And finally the upload-form.php
<?php
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));
header('Content-type: application/json');
require 'php-mailer/class.phpmailer.php';
$to = 'xxx#xxx.xxx';
$subject = $_POST['subject'];
if($to) {
$name = $_POST['name'];
$email = $_POST['email'];
$fields = array(
0 => array(
'text' => 'Name',
'val' => $_POST['name']
),
1 => array(
'text' => 'Email address',
'val' => $_POST['email']
),
2 => array(
'text' => 'File',
'val' => $_POST['file_upload']
)
);
$message = "";
foreach($fields as $field) {
$message .= $field['text'].": " . htmlspecialchars($field['val'], ENT_QUOTES) . "<br>\n";
}
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->From = $email;
$mail->FromName = $_POST['name'];
$mail->AddAttachment = $_POST['file_uploaded']; // attachment
$mail->AddAddress($to); // Add a recipient
$mail->AddReplyTo($email, $name);
);
$mail->IsHTML(true); // Set email format to HTML
$mail->CharSet = 'UTF-8';
$mail->Body = $name;
if(!$mail->Send()) {
$arrResult = array ('response'=>'error');
}
I searched everywhere, everything I got was people saying to add a
$mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
but it doesn't seem to work, the only answers I found on google were to attach files already on the server, but I want to attach files uploaded by users and then sent to my email, and if possible i want the files to be a temp file.
I'm a noob with PHP, so please help me. What am I doing wrong?
This should work to grab the file attachment and send it to your email
$mail->AddAttachment($_FILES['upload']['tmp_name']);
in $_FILES() the ['upload'] keyword represents the name of your file input. So adjust that accordingly.
If you want to send yourself an attachment with the actual attachment name, try this.
$mail->AddAttachment($_FILES['upload']['tmp_name'], $_FILES['upload']['name']);
What I've found to work pretty easy is set $_FILES['upload']['tmp_name'] and $_FILES['upload']['name'] as a variables.
So,
$file = $_FILES['upload']['tmp_name']
$file_name = $_FILES['upload']['name']
$mail->AddAttachment($file, $file_name );

Categories

Resources