Attaching and Sending files with PHPMailer - javascript

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 );

Related

Access multiple files from multiple file inputs using $_FILES after using FormData (And add to ACF data on WP Backend)

Using Wordpress, I'm attempting to access files from one out of two file inputs using $_FILES but running into some problems:
To outline - I'm using a front-end form that has two file fields, both of which accept multiple files:
<form id="form" action="" method="post">
<input type="text" name="my_name">
<input type="file" name="reference_images[]" multiple>
<input type="file" name="photo_of_area[]" multiple>
</form>
The file inputs will be taking images, and I need to upload images from "reference_images" to one repeater field, ad "photo_of_area" to another repeater field. This form is posted via AJAX using FormData - the functions for this are below:
function saveForm(varform) {
blockUI();
jQuery.ajax({
type: "POST",
url: window.ajaxObject.ajaxUrl,
dataType: "JSON",
data: varform,
processData: false,
contentType: false,
cache: false,
success: onSuccesPing(),
crossDomain:true,
});
}
jQuery('#form').submit(function(event) {
event.preventDefault(); // Prevent form submitting as normal
var formData = new FormData(jQuery('#form')[0]);
formData.append("action", "messaging_post");
saveForm(formData);
});
I then have a function handle the messaging_post action which is below, this creates a new post with the form data, and loops over the attached images and injects them to my ACF repeater:
add_action( 'wp_ajax_messaging_post', 'messaging_post' );
add_action('wp_ajax_nopriv_messaging_post', 'messaging_post');
function messaging_post(){
if(isset($_POST['my_name'])) {
$name = sanitize_text_field($_POST['my_name']);
$new_post = array(
'ID' => '',
'post_type' => 'quote_requests',
'post_status' => 'publish',
'post_title' => $title,
'post_content' => '',
);
$post_id = wp_insert_post($new_post);
$post = get_post($post_id);
update_field('name', $name, $post_id); // Updates the ACF text field 'name' for the inserted post
// Works, but uploads files from BOTH file inputs to the single ACF repeater:
foreach($_FILES as $value){
for ($i=0; $i <count($value['name']); $i++) {
$errors= array();
$file_name = $value['name'][$i];
$file_size = $value['size'][$i];
$file_tmp = $value['tmp_name'][$i];
$file_type = $value['type'][$i];
$file_ext=strtolower(end(explode('.',$value['name'][$i])));
if(empty($errors)==true) {
$wordpress_upload_dir = wp_upload_dir();
$profilepicture = $wordpress_upload_dir['path'].'/';
move_uploaded_file($file_tmp, $profilepicture.$file_name);
} else{
print_r($errors);
}
$file_name_and_location = $profilepicture.$file_name;
$file_title_for_media_library = $value['name'][$i];
$fildename = $value['name'][$i];
$arr_file_type = wp_check_filetype(basename($fildename));
$uploaded_file_type = $arr_file_type['type'];
$attachment = array(
'post_mime_type' => $uploaded_file_type,
'post_title' => addslashes($file_title_for_media_library),
'post_content' => $fildename,
'post_status' => 'inherit',
'post_parent' => 0,
'post_author' => get_current_user_id(),
);
wp_read_image_metadata( $file_name_and_location );
$attach_id = wp_insert_attachment( $attachment, $file_name_and_location,true,false);
$attach_data = wp_generate_attachment_metadata($attach_id,$file_name_and_location );
wp_update_attachment_metadata( $attach_id, $attach_data );
$images[]= array("image" => $attach_id);
}
}
update_field('photo_area', $images, $post_id);
}
}
The above works, and populates the created post with the name from the form, but this attaches files from BOTH the reference_images and photo_of_area to the photo_area ACF repeater.
When trying to access $_FILES using a function such as the following:
foreach($_FILES["photo_of_area"] as $value){
for ($i=0; $i <count($value['name']); $i++) {
$errors= array();
$file_name = $value['name'][$i];
$file_size = $value['size'][$i];
$file_tmp = $value['tmp_name'][$i];
$file_type = $value['type'][$i];
$file_ext=strtolower(end(explode('.',$value['name'][$i])));
if(empty($errors)==true) {
$wordpress_upload_dir = wp_upload_dir();
$profilepicture = $wordpress_upload_dir['path'].'/';
move_uploaded_file($file_tmp, $profilepicture.$file_name);
} else{
print_r($errors);
}
$file_name_and_location = $profilepicture.$file_name;
$file_title_for_media_library = $value['name'][$i];
$fildename = $value['name'][$i];
$arr_file_type = wp_check_filetype(basename($fildename));
$uploaded_file_type = $arr_file_type['type'];
$attachment = array(
'post_mime_type' => $uploaded_file_type,
'post_title' => addslashes($file_title_for_media_library),
'post_content' => $fildename,
'post_status' => 'inherit',
'post_parent' => 0,
'post_author' => get_current_user_id(),
);
wp_read_image_metadata( $file_name_and_location );
$attach_id = wp_insert_attachment( $attachment, $file_name_and_location,true,false);
$attach_data = wp_generate_attachment_metadata($attach_id,$file_name_and_location );
wp_update_attachment_metadata( $attach_id, $attach_data );
$images[]= array("image" => $attach_id);
}
}
update_field('photo_area', $images, $post);
This doesn't seem to work and returns nothing.
I'm assuming that after going through FormData(), the files are now not accessible on the normal $_FILES['name_of_input'], and should rather have something else done with them?
I've also tried just appending the images to the FormData, but seemed to be having the same issue.
Would anyone be able to shed some light on how I could access $_FILES["photo_of_area"], and also $_FILES["reference_images"] independently of each other after being passed through FormData()? Or any alternative ways that I should look at to achieve the desired behaviour.
Ideally, I need to access images from each file input respectively.
Thanks!
I've managed to achieve this by changing my loop over the $_FILES array as such:
$photo_of_area = $_FILES["photo_of_area"];
foreach ($photo_of_area['name'] as $key => $value) {
$errors = array();
$file_name = $photo_of_area['name'][$key];
$file_size = $photo_of_area['size'][$key];
$file_tmp = $photo_of_area['tmp_name'][$key];
$file_type = $photo_of_area['type'][$key];
$file_ext = strtolower(end(explode('.',$photo_of_area['name'][$key])));
if (empty($errors) == true) {
$wordpress_upload_dir = wp_upload_dir();
$upload_dir_path = $wordpress_upload_dir['path'].'/';
move_uploaded_file($file_tmp, $upload_dir_path.$file_name);
} else {
print_r($errors);
}
$file_name_and_location = $upload_dir_path.$file_name;
$file_title_for_media_library = $photo_of_area['name'][$key];
$fildename = $photo_of_area['name'][$key];
$arr_file_type = wp_check_filetype(basename($fildename));
$uploaded_file_type = $arr_file_type['type'];
$attachment = array(
'post_mime_type' => $uploaded_file_type,
'post_title' => addslashes($file_title_for_media_library),
'post_content' => $fildename,
'post_status' => 'inherit',
'post_parent' => 0,
'post_author' => get_current_user_id(),
);
wp_read_image_metadata( $file_name_and_location );
$attach_id = wp_insert_attachment( $attachment, $file_name_and_location,true,false);
$attach_data = wp_generate_attachment_metadata($attach_id,$file_name_and_location );
wp_update_attachment_metadata( $attach_id, $attach_data );
$area_photos_array[] = array("image" => $attach_id);
}
update_field('photo_area', $area_photos_array, $post_id);
This successfully injects each image uploaded to a new row of the photo_area repeater inside the current post specified by $post_id.

How to make it mandatory to check the form's checkbox?

I have a form configured with PHP and I'm lost, I do not know how to make it mandatory to check the checkbox that I put in the terms and conditions. I have put the ID but I do not know how to put it in the PHP file. I do not know if I should add something to the javascript file. I show you the three files so they can tell me how to correct the errors, rather I should add to the PHP file.
I have added the PHP code along with the Javascript since I do not know how to add it in any other way.
The form when I give to send shows me the following:
There was an error sending the form. Please try again later
I have several errors in the console when sending the form:
POST https://agrochema.000webhostapp.com/includes/contact.php net::ERR_NAME_NOT_RESOLVED
send # jquery-1.12.4.js:17
ajax # jquery-1.12.4.js:17
(anonymous) # form-script.js:21
dispatch # jquery-1.12.4.js:16
r.handle # jquery-1.12.4.js:16
-- XHR failed loading: POST "https://agrochema.000webhostapp.com/includes/contact.php"
s
end # jquery-1.12.4.js:17
ajax # jquery-1.12.4.js:17
(anonymous) # form-script.js:21
dispatch # jquery-1.12.4.js:16
r.handle # jquery-1.12.4.js:16
Thank you
// Archivo PHP
<?php
//require_once('phpmailer/class.phpmailer.php');
require_once('phpmailer/PHPMailerAutoload.php');
$mail = new PHPMailer();
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'tls://smtp.gmail.com:587'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'example#gmail.com'; // SMTP username
$mail->Password = 'Password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$message = "";
$status = "false";
$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';
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if( $_POST['form_name'] != '' AND $_POST['form_email'] != '' ) {
$name = $_POST['form_name'];
$email = $_POST['form_email'];
$message = $_POST['form_message'];
$botcheck = $_POST['form_botcheck'];
$toemail = 'miguelestabaenlaparra#gmail.com'; // Your Email Address
$toname = 'Unlock Design'; // Your Name
if( $botcheck == '' ) {
$mail->SetFrom( $email , $name );
$mail->AddReplyTo( $email , $name );
$mail->AddAddress( $toemail , $toname );
$name = isset($name) ? "Name: $name<br><br>" : '';
$email = isset($email) ? "Email: $email<br><br>" : '';
$message = isset($message) ? "Message: $message<br><br>" : '';
$referrer = $_SERVER['HTTP_REFERER'] ? '<br><br><br>This Form was submitted from: ' . $_SERVER['HTTP_REFERER'] : '';
$body = $name.' '.$email.' '.$message.' '.$referrer;
$mail->MsgHTML( $body );
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
));
$sendEmail = $mail->Send();
if( $sendEmail == true ):
$responseArray = array('type' => 'success', 'message' => $okMessage);
else:
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
endif;
} else {
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
} else {
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
} else {
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
//$status_array = array( 'message' => $message, 'status' => $status);
//echo json_encode($status_array);
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'];
}
?>
// ARCHIVO JAVASCRIPT
// CONTACT FORM 2 SCRIPT
// ===========================
$(function () {
$('#contact_form2').validator();
$('#contact_form2').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "includes/contact2.php";
$.ajax({
type: "POST",
url: url,
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) {
$('#contact_form2').find('.messages').html(alertBox).fadeIn('slow');
$('#contact_form2')[0].reset();
setTimeout(function(){ $('.messages').fadeOut('slow') }, 6000);
}
}
});
return false;
}
})
});
<DOCTYPE html>
<body>
<section class="ulockd-contact-page">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="ulockd-contact-form ulockd-style-two">
<form id="contact_form" name="contact_form" class="contact-form" action="includes/contact.php" method="post"
novalidate="novalidate">
<div class="messages"></div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input id="form_name" name="form_name" class="form-control ulockd-form-fg required" placeholder="Nombre"
required="required" data-error="Nombre requerido." type="text">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input id="form_email" name="form_email" class="form-control ulockd-form-fg required email"
placeholder="Email" required="required" data-error="Email requerido." type="email">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input id="form_phone" name="form_phone" class="form-control ulockd-form-fg required" placeholder="Teléfono"
required="required" data-error="Numero de telefono requerido." type="text">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input id="form_subject" name="form_subject" class="form-control ulockd-form-fg required"
placeholder="Tema" required="required" data-error="Tema requerido." type="text">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<textarea id="form_message" name="form_message" class="form-control ulockd-form-tb required" rows="8"
placeholder="Su mensaje" required="required" data-error="Mensaje requerido."></textarea>
<div class="help-block with-errors"></div>
</div>
<input type="checkbox" name="aceptar_terminos" id="aceptar_terminos" value="aceptar_terminos" /> He leído y acepto los terminos y condiciones
<div class="form-group ulockd-contact-btn">
<input id="form_botcheck" name="form_botcheck" class="form-control" value="" type="hidden">
<button type="submit" class="btn btn-default btn-lg ulockd-btn-thm" data-loading-text="Getting Few Sec...">ENVIAR</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
</body>
</html>
First make your field required (required="required") on HTML form for JS validation:
<input
type="checkbox"
name="aceptar_terminos"
id="aceptar_terminos"
value="aceptar_terminos"
required="required"
/>
As you are using serialize() the checkbox values will only send it if its checked, then you can validate on your PHP as well. Like:
if(
!empty($_POST['form_name']) AND
!empty($_POST['form_email']) AND
!empty($_POST['aceptar_terminos']) AND
$_POST['aceptar_terminos'] == 'aceptar_terminos'
) { ... }
Also update your PHP to only require the files and call the class if the form is valid:
<?php
$message = "";
$status = "false";
$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';
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if(
!empty($_POST['form_name']) AND
!empty($_POST['form_email']) AND
!empty($_POST['aceptar_terminos']) AND
$_POST['aceptar_terminos'] == 'aceptar_terminos'
) {
//require_once('phpmailer/class.phpmailer.php');
require_once('phpmailer/PHPMailerAutoload.php');
$mail = new PHPMailer();
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'tls://smtp.gmail.com:587'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'example#gmail.com'; // SMTP username
$mail->Password = 'Password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$name = $_POST['form_name'];
$email = $_POST['form_email'];
$message = $_POST['form_message'];
$botcheck = $_POST['form_botcheck'];
$toemail = 'miguelestabaenlaparra#gmail.com'; // Your Email Address
$toname = 'Unlock Design'; // Your Name
if( $botcheck == '' ) {
$mail->SetFrom( $email , $name );
$mail->AddReplyTo( $email , $name );
$mail->AddAddress( $toemail , $toname );
$name = isset($name) ? "Name: $name<br><br>" : '';
$email = isset($email) ? "Email: $email<br><br>" : '';
$message = isset($message) ? "Message: $message<br><br>" : '';
$referrer = $_SERVER['HTTP_REFERER'] ? '<br><br><br>This Form was submitted from: ' . $_SERVER['HTTP_REFERER'] : '';
$body = $name.' '.$email.' '.$message.' '.$referrer;
$mail->MsgHTML( $body );
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
));
$sendEmail = $mail->Send();
if( $sendEmail == true ):
$responseArray = array('type' => 'success', 'message' => $okMessage);
else:
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
endif;
} else {
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
} else {
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
} else {
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
//$status_array = array( 'message' => $message, 'status' => $status);
//echo json_encode($status_array);
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'];
}
?>

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);
}
}

php sends blank e-mail

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.

Send and image from PHP to Javascript (JSON)

I'm trying to make a "meal" in my DB, so in my website i made a form with a name, and a picture. This is the code of the form :
<?php
$new_meal_title = htmlentities($_POST["new_meal_title"]);
$new_meal_img = htmlentities($_POST["new_meal_img"]);
$data = array(
'new_meal_title' => $new_meal_title,
'new_meal_img' => base64_encode($new_meal_img)
);
$options = array(
'http' => array(
'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(constant("API_URL")."/meal", false, $context);
if($result === FALSE){
var_dump($result);
}
$json = json_decode($result);
if($json->success == "true"){
header('Location: ../../');
return;
}
else{
echo $json->message;
}
header('Location: ../../');
?>
The form is sending data to my Node API. My Question is, how to save into a folder the image path through form in Javascript after it has been received in JSON.
Thanks for your help, i just had to change this line :
$new_meal_img = htmlentities($_POST["new_meal_img"]);
By
$new_meal_img = $_FILES['new_meal_img']["tmp_name"];
And
'new_meal_img' => base64_encode($new_meal_img)
By
'new_meal_img' => base64_encode(file_get_contents($new_meal_img))

Categories

Resources