So I submit my form and and every time I click ctrl-r it refreshes the page without alerting me it will resubmit the form. Every time I click the reload button on browser it asks me that it will reload but I already submitted the form so now I am getting a new submit every time and creating a new item in my sqlDB. I refresh and I do not know what I have to do to automatically refresh the page to where it wont save the form resubmit and is like a new page again.
where the //end else is at is where I have tried adding a header(Location:) but I get an error. I posted the error more to the bottom of the question.
footer.php
<?php
if(isset($_POST['submit-story'])){
$answer = $_POST['human-story'];
if (!ctype_digit($answer) == 8) {
echo "Cannot store event. wrong answer";
die();
} else {
//Get the uploaded file information
$name_of_uploaded_file = basename($_FILES['uploaded_file']['name']);
//get the file extension of the file
$type_of_uploaded_file =
substr($name_of_uploaded_file,
strrpos($name_of_uploaded_file, '.') + 1);
$size_of_uploaded_file =
$_FILES["uploaded_file"]["size"]/1024;//size in KBs
//Settings
$max_allowed_file_size = 1000000; // size in KB
$allowed_extensions = array("jpg","jpeg","gif","bmp","mp4", "mov");
//Validations
if($size_of_uploaded_file > $max_allowed_file_size )
{
$errors = "\n Size of file should be less than $max_allowed_file_size";
}
//------ Validate the file extension -----
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
{
$allowed_ext = true;
}
}
if(!$allowed_ext)
{
$errors = "\n The uploaded file is not supported file type. ".
"Only the following file types are supported: ".implode(',',$allowed_extensions);
}
//copy the temp. uploaded file to uploads folder
$upload_folder = 'uploads/';
$to = "example#gmail.com"; // this is your Email address
$first_name = filter_var($_POST['first_name']. $schoolOfficialShortName, FILTER_SANITIZE_STRING);
$story = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
$eventDate = filter_var($_POST['eventDate'],FILTER_SANITIZE_STRING);
$eventLocation = filter_var($_POST['eventLocation'],FILTER_SANITIZE_STRING);
$subject = "blah-" . $schoolOfficialShortName . "Event";
$title = filter_var($_POST['title'], FILTER_SANITIZE_STRING);
$message = $first_name . " wrote the following:" . "\n\n" . $title ."<br>". $story;
$headers = "From: $first_name";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
$content = '';
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if($tmp_path) {
$filename = $_FILES["uploaded_file"]["name"];
$path_of_uploaded_file = $upload_folder . $filename;
if(!copy($tmp_path, $path_of_uploaded_file))
{
$errors = '\n error while copying the uploaded file';
}
$file_size = filesize($path_of_uploaded_file);
$handle = fopen($path_of_uploaded_file, "rb");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
}
// if attachment has successfully encoded
if ($content) {
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"{$filename}\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"{$filename}\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $content . "\n\n";
$message .= "--{$mime_boundary}\n";
}
$headers2 = "From:" . $to;
mail($to, $subject, $message, $headers);
//send items to S3 bucket
move_uploaded_file($upload_folder, $filename);
//store image to s3 bucket
try {
$result = $s3->putObject([
'Bucket' => $config['s3']['bucket'],
'Key' => "uploads/{$name_of_uploaded_file}",
'Body' => fopen($path_of_uploaded_file, 'rb'),
'ACL' => 'public-read'
]);
$results = $result['ObjectURL'];
if (is_uploaded_file($_FILES['uploaded_file']['tmp_name'])){
//inserts in pending table
$sql = "INSERT INTO items (photo,title,eventDate,description,name,pLike,pDislike,address) VALUES ( :photo, :title, :eventDate, :description, :name, :pLike, :pDislike, :address)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':photo', $results);
$stmt->bindParam(':description', $story);
$stmt->bindParam(':eventDate', $eventDate);
$stmt->bindParam(':address', $eventLocation);
$stmt->bindParam(':name', $first_name);
$stmt->bindValue(':pLike', 0, PDO::PARAM_INT);
$stmt->bindValue(':pDislike', 0, PDO::PARAM_INT);
$stmt->execute();
}else {
die("<h1>There was an error. Please go back and retry.</h1>");
}
//remove the pending file in uploads folder
unlink($path_of_uploaded_file);
} catch(PDOException $e){
echo 'error in query: '.$e->getMessage();
}
};// end else
};// end isset final
?>
I have tried adding a header(Location: index.php) But i get a weird error saying
Cannot modify header information - headers already sent by (output started at /Users/mine/Documents/www/website/schools/inc/header.php:67) in /Users/mine/Documents/www/website/schools/inc/footer.php on line 127
Unset $_POST variable after proccessing data in your footer.php
your header already send problem : It means some text was already outputted. Place your header() on top of your script. Or look at the ob_start and ob_end_clean() functions.
You can not use header() once text has been output to the browser. As your header file include presumably outputs HTML, header() cannot be used.
You can solve this in flowing ways:
Move the if statement above the header file include.
ob_start() at the top of the script to buffer the output.
Related
This is my contact-form-handler.php file. After clicking submit button, I want an alert in PHP. I am receiving Mail successfully and redirect to my main page but without an alert message. How can I use the alert box in PHP?
My form is working fine, but this time I stucked in this simple task.
<?php
if(isset($_POST['submit'])){
//$companyMail = 'enesh#gmail.com';
$to = "eneshpal#gmail.com"; // this is your Email address
$customerMail = $_POST['formEmail']; // this is the sender's Email address
$first_name = $_POST['formFirstName'];
$last_name = $_POST['formLastName'];
$phone = $_POST['formPhone'];
$text = $_POST['formText'];
/* foreach($_POST['project_type'] as $project_type_value){} */
$projectType = implode(', ',$_POST['project_type']);
$scopeProject = implode(', ',$_POST['scope_project']);
$project_type_Str = 'Project Type : '.$projectType;
$scope_project_Str = 'Scope of Project : '.$scopeProject;
$subject = "Form Submission";
$message = "Hi, \n\n";
$message .= "First Name: ".$first_name . "\nLast Name: " . $last_name . " \nEmail: " . $customerMail . " \nPhone : " . $phone . "\nDescription: " . $text . "\n";
$message .= $project_type_Str."\n";
$message .= $scope_project_Str;
//$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
//$headers = "From:" . $companyMail;
//$headers2 = "From:" . $to;
if(mail($to,$subject,$message)){
//echo 'Mail Sent';
//$message = "Thanks, We Will Contact you Shortly";
//echo "<script type='text/javascript'>alert('$message');</script>";
echo "<script>alert('Thanks, We Will Contact you Shortly');</script>";
header('Location:get_estimation.php');
}else{
echo 'Mail Not Sent';
}
//mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
/*if( "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.")
else die; */
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
?>
In your case it would be better to redirect the user
header('Location:get_estimation.php?success=true');
and pass a GET-parameter.
When the GET-Parameter is set it will display what you want on your get_estimation.php-page
There are many problems with your script, but to answer your key question... you are echo'ing out the javascript code for an alert(), which will in turn prevent your php header('Location:get_estimation.php'); from executing because there has already been output sent to the browser before header was called. See here for more info.
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
As per your comment above...
Yes Sir I want just just wish to render a success message after the form has been submitted?
To give you an example of how to achieve what you need for this...
<?php
if (!empty($_GET['success'])) {
echo 'Thanks, we will contact you shortly';
exit;
}
if (isset($_POST['submit'])) {
$to = "eneshpal#gmail.com";
$customerMail = $_POST['formEmail'];
$first_name = $_POST['formFirstName'];
$last_name = $_POST['formLastName'];
$phone = $_POST['formPhone'];
$text = $_POST['formText'];
$projectType = implode(', ', $_POST['project_type']);
$scopeProject = implode(', ', $_POST['scope_project']);
$project_type_Str = 'Project Type : ' . $projectType;
$scope_project_Str = 'Scope of Project : ' . $scopeProject;
$subject = "Form Submission";
$message = "Hi, \n\n";
$message .= "First Name: " . $first_name . "\nLast Name: " . $last_name . " \nEmail: " . $customerMail . " \nPhone : " . $phone . "\nDescription: " . $text . "\n";
$message .= $project_type_Str . "\n";
$message .= $scope_project_Str;
if (mail($to, $subject, $message)) {
header('Location: get_estimation.php?success=1');
exit;
} else {
echo 'Mail Not Sent';
exit;
}
}
To explain, you should not be using a browser-native javascript alert rendered from php to pop-up and notify the user of a form submission success, especially immediately after a redirect. It's just a bad user experience, it hijacks the browser window until they click ok on it and you cannot really style native alert windows etc.
Instead you should redirect with a success GET variable after the mail is sent successfully (back to the original page, presuming that is get_estimation.php in my example - but you can redirect elsewhere to another script). Then you can detect the presence of this variable in the script redirected to and show an appropriate message etc.
echo "Thank You,will contact you soon";
echo "<script>setTimeout(\"location.href = 'get_estimation.php';\",3000); </script>";
Sorry for the title gore I am a little over my head on this one and have tried everything I can find online. I'm trying to pass data via post to my sendjs.php file and I have an issue.
The ajax success function does not apply the if statement.
Live site here: www.diysoakwells.com.au (you can add an item and checkout to test).
I'm not even sure where to start to be honest so any information would be appreciated and I will update the post with any info as requested.
app.js
$(function() {
// Get the form.
var form = $("#ajax-contact");
// Get the messages div.
var formMessages = $("#form-messages");
var spinner = $("#spinner");
var submit = $("#submit");
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
//display the cog animation
$(spinner).removeClass("hidden");
//hide the submit button
$(submit).addClass("hidden");
jsonObj=[];
for(i=1;i<$(".item-price").length;i++)
{
var items={};
var itemname = $(".item-name").get(i);
var itemprice = $(".item-price").get(i);
var itemquantity = $(".item-quantity").get(i);
var itemtotal = $(".item-total").get(i);
items["name"] = itemname.innerHTML;
items["price"] = itemprice.innerHTML;
items["quantity"] = itemquantity.innerHTML;
items["total"] = itemtotal.innerHTML;
jsonObj.push(items);
}
console.log(items);
var formdata = {};
formdata["textbox"] = $("#textbox").val();
formdata["name"] = $("#name").val();
formdata["phone"] = $("#phone").val();
formdata["email"] = $("#email").val();
formdata["address"] = $("#address").val();
formdata["grandtotal"] = simpleCart.grandTotal();
var x =
{
"cart" : jsonObj,
"formdata" : formdata,
"captchaResponse" : $("#g-recaptcha-response").val()
};
//jsonString = jsonObj+formdata;
var y = JSON.stringify(x);
console.log(y);
var result = jQuery.parseJSON(y);
console.log(result);
// Serialize the form data.
//var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: "post",
url: "sendjs.php" ,
//url: $(form).attr("action"),
data: y,
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (response) {
if(response=="Thank You! Your message has been sent.")
{
//remove the button animation
$(spinner).addClass("hidden");
$(formMessages).removeClass("error");
$(formMessages).addClass("success");
$("#textbox").val("");
$("#name").val("");
$("#email").val("");
$("#message").val("");
$("#phone").val("");
$("#address").val("");
}
else
{
$(formMessages).removeClass("success");
$(formMessages).addClass("error");
$(spinner).addClass("hidden");
$(submit).removeClass("hidden");
}
$(formMessages).text(response);
}
});
});
});
sendjs.php
<?php
//Debugging
//ini_set( 'display_errors', 1 );
//error_reporting( E_ALL );
//replaces file_get_contents due to restrictions on server
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
//turn url_fopen on due to restrictions on server
//ini_set('allow_url_fopen', true);
date_default_timezone_set('Australia/Perth');
$time = date ("h:i A");
$date = date ("l, F jS, Y");
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$captcha = $obj["captchaResponse"];
$captcha;
$secretKey = "scrubbed";
$ip = $_SERVER['REMOTE_ADDR'];
$response = get_data("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
//not used due to server restictions
//$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo "Please Click on the Captcha";
return false;
}
else
{
//echo $items;
$name = $obj["formdata"]["name"];
$phone = $obj["formdata"]["phone"];
$email = $obj["formdata"]["email"];
$textbox = $obj["formdata"]["textbox"];
$address = $obj["formdata"]["address"];
$grandtotal = $obj["formdata"]["grandtotal"];
$text = "<html style='font-family:arial'>
<body>
<h1 style='color:crimson;'>DIY Soakwells</h1>
<p>This order was submitted from www.diysoakwells.com.au on $date at $time</p>
<p>$name thank you for your order inquiry. Deliveries are normally every Friday, we will be in contact shortly to discuss your order and confirm a time.</p>
<p>An invoice will be issued after delivery for payment via bank transfer.</p>
<p>In the meantime if you haven't already seen it, you can take a look at www.soakwellcalculator.com.au to confirm the number of soakwells you ordered will be adequate.</p>
<br>
<h2 style='color:crimson;'>CUSTOMER DETAILS</h2>
<p><b>Email:</b>\n$email</p>
<p><b>Name:</b>\n$name</p>
<p><b>Phone:</b>\n$phone</p>
<p><b>Delivery Address:</b>\n$address</p>
<p><b>Message:</b>\n$textbox</p>
<br>
<h2 style='color:crimson;'>ORDER DETAILS</h2>";
$items_in_cart = count($obj["cart"]);
for($i=0; $i < $items_in_cart; $i++) {
$iname = $obj["cart"][$i]["name"];
$price = $obj["cart"][$i]["price"];
$quantity = $obj["cart"][$i]["quantity"];
$total = $obj["cart"][$i]["total"];
//display looped cart data
$items .= "<p>$iname x $quantity - $price <small>ea.</small> <b>Sub Total: </b> $total .</p>";
}
$final_total ="<br>
<p><b>Total: </b>$$grandtotal <small>inc. GST</small></p>
</body>
</html>";
//Email Content
$body = $text.$items.$final_total;
// Set the email subject.
$subject = "New order from $name";
// Build the email content.
$email_content = $body;
// Build the email headers.
$email_headers = 'MIME-Version: 1.0' . PHP_EOL;
$email_headers .= 'Content-Type: text/html; charset=ISO-8859-1' . PHP_EOL;
//$email_headers .= 'To:' . $name . '<' . $email . '>' . PHP_EOL;
$email_headers .= 'From: DIY Soakwells <orders#diysoakwells.com>' . PHP_EOL;
$email_headers .= 'CC: orders#diysoakwells.com.au' . PHP_EOL;
$email_headers .= 'Reply-To: DIY Soakwells <orders#diysoakwells.com.au>' . PHP_EOL;
$email_headers .= 'Return-Path: DIY Soakwells <orders#diysoakwells.com>' . PHP_EOL;
$email_headers .= 'X-Sender: DIY Soakwells <orders#diysoakwells.com.au' . PHP_EOL;
$email_headers .= 'X-Mailer: PHP/' . phpversion() . PHP_EOL;
//$email_headers .= 'X-Priority: 1' . PHP_EOL;
//validate Email
$email_check = filter_input(INPUT_POST, $email, FILTER_VALIDATE_EMAIL);
//Recipients
$to = $email;
if (mail($to, $subject, $email_content, $email_headers, '-forders#diysoakwells.com.au')) {
// Set a 200 (okay) response code.
//http_response_code(200);
echo "Thank You. Your order has been sent and a copy mailed to your inbox.";
} else {
// Set a 500 (internal server error) response code.
//http_response_code(500);
echo "There appears to be an issue with our server, please ring 0420 903 950 or email contact#diysoakwells.com.au.";
}
}
?>
Hope someone can give me some tips.
because your condition is response == "Thank You! Your message has been sent."
and your results are
"Please Click on the Captcha", "Thank You. Your order has been sent and a copy mailed to your inbox.", "There appears to be an issue with our server, please ring 0420 903 950 or email contact#diysoakwells.com.au.".
so all of your result will do else part
I've tried so many variables and been at this for hours and hours for something I know will be so simple haha, but I cannot get this to work... All I need to do, is... when the form is completed I have it redirected to a page instead of the normal error message.
Your help is appreciated.
<?php
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$phone = ($_GET['phone']) ? $_GET['phone'] : $_POST['phone'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$comment = ($_GET['comment']) ?$_GET['comment'] : $_POST['comment'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//Simple server side validation for POST data, of course, you should validate the email
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$phone) $errors[count($errors)] = 'Please enter your contact number.';
if (!$email) $errors[count($errors)] = 'Please enter your email.';
if (!$comment) $errors[count($errors)] = 'Please enter your comment.';
//if the errors array is empty, send the mail
if (!$errors) {
//recipient - replace your email here
$to = 'me#myemail.com';
//sender - from the form
$from = $name . ' <' . $email . '>';
//subject and the html message
$subject = 'Message from ' . $name;
$message = 'Name: ' . $name . '<br/><br/>
Phone: ' . $phone . '<br/><br/>
Email: ' . $email . '<br/><br/>
Message: ' . nl2br($comment) . '<br/>';
//send the mail
$result = sendmail($to, $subject, $message, $from);
//if POST was used, display the message straight away
if ($_POST) {
if ($result)
echo 'Thank you! We have received your message.';
else
echo 'Sorry, unexpected error. Please try again later';
//else if GET was used, return the boolean value so that
//ajax script can react accordingly
//1 means success, 0 means failed
} else {
echo $result;
}
//if the errors array has values
} else {
//display the errors message
for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
echo 'Back';
exit;
}
//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
if ($result)
return 1;
else
return 0;
}
I have a "contact us" form and everything is working but my error callback in the ajax runs instead of the success. I ajax is called, the PHP file runs, and I get an email to my localhost (using Mercury).
So why is my success callback not running? I have no idea how to find out what is causing the error especially since everything works.
The only thing I suspect is the file folders. The current structure is this. My html file and php file are in the root directory. The JS file is in a folder.
Here is a screenshot of the network tab in chrome debugger after I press submit
http://i.imgur.com/HfRYjj0.png
My Ajax:
$(document).ready(function(e) {
$("#main-contact-form").on('submit', (function(e) {
e.preventDefault();
$('#sendingemail').fadeIn();
$.ajax({
url : "../sendemail.php",
type : "POST",
data : new FormData(this),
contentType : false,
cache : false,
processData : false,
success : function(data) {
$('#sendingemail').fadeOut();
$('#emailsent').fadeIn();
},
error : function() {
alert("Error");
}
});
}));
});
My PHP:
<?php
// ini_set('display_errors', 'On');
// error_reporting(E_ALL);
header('Content-type: application/json');
// WE SHOULD ASSUME THAT THE EMAIL WAS NOT SENT AT FIRST UNTIL WE KNOW MORE.
// WE ALSO ADD AN ATTACHMENT KEY TO OUR STATUS ARRAY TO INDICATE THE STATUS OF OUR ATTACHMENT:
/*$status = array(
'type'=>'Error',
'message'=>'Couldn\'t send the Email at this Time. Something went wrong',
'attachement'=>'Couldn\'t attach the uploaded File to the Email.'
);*/
//Added to deal with Files
require_once ('PHPMailer/class.phpmailer.php');
if (isset($_FILES['uploaded_file'])) {
//require_once('/PHPMailer/class.smtp.php');
//Get the uploaded file information
$name_of_uploaded_file = basename($_FILES['uploaded_file']['name']);
//get the file extension of the file
$type_of_uploaded_file = substr($name_of_uploaded_file, strrpos($name_of_uploaded_file, '.') + 1);
$size_of_uploaded_file = $_FILES["uploaded_file"]["size"] / 1024;
//size in KBs
//Settings
$max_allowed_file_size = 10240;
// size in KB
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp", "png");
//Validations
if ($size_of_uploaded_file > $max_allowed_file_size) {
$errors .= "\n Size of file should be less than $max_allowed_file_size (~10MB). The file you attempted to upload is too large. To reduce the size, open the file in an image editor and change the Image Size and resave the file.";
}
//------ Validate the file extension -----
$allowed_ext = false;
for ($i = 0; $i < sizeof($allowed_extensions); $i++) {
if (strcasecmp($allowed_extensions[$i], $type_of_uploaded_file) == 0) {
$allowed_ext = true;
}
}
if (!$allowed_ext) {
$errors .= "\n The uploaded file is not supported file type. " . " Only the following file types are supported: " . implode(',', $allowed_extensions);
}
//copy the temp. uploaded file to uploads folder - make sure the folder exists on the server and has 777 as its permission
$upload_folder = "temp/";
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if (is_uploaded_file($tmp_path)) {
if (!copy($tmp_path, $path_of_uploaded_file)) {
$errors .= '\n error while copying the uploaded file';
}
}
}
//--end
$name = #trim(stripslashes($_POST['name']));
$clientemail = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $clientemail . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$email = new PHPMailer();
$email -> From = $clientemail;
$email -> FromName = $name;
$email -> Subject = $subject;
$email -> Body = $body;
$email -> AddAddress('root#localhost.com');
//Send to this email
// EXPLICITLY TELL PHP-MAILER HOW TO SEND THE EMAIL... IN THIS CASE USING PHP BUILT IT MAIL FUNCTION
$email -> isMail();
// THE AddAttachment METHOD RETURNS A BOOLEAN FLAG: TRUE WHEN ATTACHMENT WAS SUCCESSFUL & FALSE OTHERWISE:
// KNOWING THIS, WE MAY JUST USE IT WITHIN A CONDITIONAL BLOCK SUCH THAT
// WHEN IT IS TRUE, WE UPDATE OUR STATUS ARRAY...
if (isset($_FILES['uploaded_file'])) {
if ($email -> AddAttachment($path_of_uploaded_file, $name_of_uploaded_file)) {
//$status[] = 'The Uploaded File was successfully attached to the Email.';
}
}
// NOW, TRY TO SEND THE EMAIL ANYWAY:
try {
$success = $email -> send();
//$status['type'] = 'success';
$status[] = 'Thank you for contacting us. We will reply as soon as possible.';
} catch(Exception $e) {
//$status['type'] ='Error';
$status[] = 'Couldn\'t send the Email at this Time. Something went wrong';
}
// SIMPLY, RETURN THE JSON DATA...
die(json_encode($status));
I am writing some code to take a page, turn it into a pdf, and email the pdf. I am using html2canvas and jsPDF to generate the pdf. I then send the pdf to a php script to process it and mail it, but this is failing. I know the pdf generation works, as I can save the pdf locally. Here is my code so far:
javascript:
$(document).ready(function() {
$('#download').click(function() {
html2canvas($('#wrapper'), {
onrendered: function(canvas) {
var imgData = canvas.toDataURL('image/png');
var doc = new jsPDF('p','mm');
doc.addImage(imgData, 'PNG', 10,10);
var pdfMail = btoa(doc.output());
$.post("../mailPdf.php",
{
data:pdfMail
},function (response,status) {
console.log(response);
});
}
});});});
mailPdf.php
function MailWithAttachment($to, $subject, $message, $senderMail, $senderName, $files){
$from = $senderName." <".$senderMail.">";
$headers = "From: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
// preparing attachments
if(count($files) > 0){
for($i=0;$i<count($files);$i++){
if(is_file($files[$i])){
$message .= "--{$mime_boundary}\n";
$fp = #fopen($files[$i],"rb");
$data = #fread($fp,filesize($files[$i]));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($files[$i])."\"\n" .
"Content-Description: ".basename($files[$i])."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($files[$i])."\"; size=".filesize($files[$i]).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
}
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $senderMail;
//send email
$mail = mail($to, $subject, $message, $headers, $returnpath);
//function return true, if email sent, otherwise return fasle
if($mail){ return TRUE; } else { return FALSE; }
}
if(!empty($_POST['data'])){
//email variables
$to = 'recipient#email.com';
$from = 'sender#email.com';
$from_name = 'From Name';
//attachment files path array
$file = base64_decode($_POST['data']);
$subject = 'PHP Email with attachment';
$html_content = '<h1>PHP Email with attachment</h1>';
//call MailWithAttachment() function and pass the required arguments
$send_email = MailWithAttachment($to,$subject,$html_content,$from,$from_name,$file);
//print message after email sent
echo $send_email?"<h1> Mail Sent</h1>":"<h1> Mail not SEND</h1>";
} else {
echo "No Data Found";
}
The script works up until the if(is_file($files[$i])){ loop. is_file always returns false and this loop fails to run. I can't figure out why its failing to recognize and read the file.
The problem with php side is that in function MailWithAttachment you are expecting a little bit different type of data for files parameter.
$file = $_POST['data']; is actually not a file, but a base64 encoded string(btoa(doc.output())). So what you actually want to do is something like this(following the signature of MailWithAttachment function).
change this:
//attachment files path array
$file = $_POST['data'];
to something like this:
//attachment file encoded
$files = array();
$file = $_POST['data'];
$filePath = '/tmp/foo.pdf';
// actually here you can do whatever you want. you just need to save file on disk, at least for request context. I think creating file in memory also should work.
file_put_contents($filePath, base64_decode($file));
$files[] = $filePath;
...
// pay attention $file is changed to $files here
MailWithAttachment(...,$files);
...