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));
Related
Good afternon, i have a form that in determined field it open a window or windows to display a specific PDF. The folder where is the path, it can there is just a PDF or a ZIP file with multiples PDF's inner according to the input filled value.
This is blur() event part on the whole my code that calls the windows and pass the values to the "arquivo.php" and "pdf.php", one is to check if is just a PDF or a ZIP, if was a PDF this return on my form informing that is a PDF just and after open just a window to display, this part is ok
JavaScript/HTML code:
///////////PASS THE VALUES TO "arquivo.php"////////////////
$.post("arquivo.php", {nprocesso: document.getElementById("processo").value}, function(data){
$( "#content3" ).html( data ); /*<-- return in this content if is a PDF or a ZIP(when is a zip it returns how many PDF's there are inner ZIP file too)*/
////////////THIS PART IS TO CREATE JUST A WINDOW OR MULTIPLES WINDOWS PASSING THE VALUES RETURNED IN THE "content3" TO "pdf.php" TO DISPLAY IT/THEM//////////////////
setTimeout(function(){
if(document.getElementById("content3").innerText == "PDF"){
window.open("pdf.php/"+document.getElementById("processo").value, '_blank', "toolbar=yes,scrollbars=yes,resizable=yes,width=800,height=800");
}else{
var QuantPDF = Number(document.getElementById("content3").innerText.slice(Number(document.getElementById("content3").innerText.lastIndexOf(','))+1, document.getElementById("content3").innerText.length));//Number(document.getElementById("content3").innerText.replace(/[^0-9]/g, ""));
var NomesPDFS = []; NomesPDFS = document.getElementById("content3").innerText.slice(3, document.getElementById("content3").innerText.length-2).split(',');
if(QuantPDF > 1){
for(var i = 0; i < QuantPDF; i++){
window.open("pdf.php/"+document.getElementById("processo").value+"/"+NomesPDFS[i], '_blank', "toolbar=yes,scrollbars=yes,resizable=yes,width=800,height=800");
}
}else{
window.open("pdf.php/"+document.getElementById("processo").value, '_blank', "toolbar=yes,scrollbars=yes,resizable=yes,width=800,height=800");
}
}
document.getElementById('closeBtn').click();
}, 1000);
}
This is the "arquivo.php", where check if is just a PDF or a ZIP file, and extract if was a zip
Arquivo.php code:
<?php
session_start();
//////////THIS PART CHECK THAT FILE IS A PDF AND RETURN TO MY JAVASCRIPT CODE/////////
if(file_exists('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'].'.pdf')){
echo 'PDF';
$_SESSION['file'] = "PDF";
}else{
//////////THIS PART CHECK THAT FILE IS A ZIP AND RETURN TO MY JAVASCRIPT CODE/////////
echo 'ZIP';
$_SESSION['file'] = "ZIP";
$zip = new ZipArchive;
$path = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'].'.zip';
///////////////////////////////////////////////////////////////////
if($zip->open($path) === true){
//////////THIS PART IT OPENS THE ZIP AND EXTRACT/////////
if(!file_exists('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'])){
mkdir('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'], 0777, true);
}
for($i = 0; $i < $zip->numFiles; $i++){
$zip->extractTo('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'], array($zip->getNameIndex($i)));
$path = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'];
$files = scandir($path); array_shift($files); array_shift($files);
$file = array(); $filename = array();
///////NOW I CATCH THE PDF's NAMES AND THE QUANTITY AND RETURN TO JAVASCRIPT CODE///////
$file[$i] = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'].'/'.$files[$i];
$filename[$i] = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'].'/'.$files[$i];
$nomes_pdfs = array();
$nomes_pdfs[$i] = substr(substr($filename[$i], strpos($filename[$i], $_POST['nprocesso'])+26, strlen($filename[$i])), 0, strpos(substr($filename[$i], strpos($filename[$i], $_POST['nprocesso'])+26, strlen($filename[$i])), '.pdf')).',';
echo $nomes_pdfs[$i];
}
$zip->close();
$path = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'];
$files = scandir($path);
array_shift($files); array_shift($files); $_SESSION['quantidade_pdf'] = count($files);
echo $_SESSION['quantidade_pdf'];
}
}
?>
My problem actually is partially on "pdf.php" where the window load with the values returned of the "content3". When is a single PDF, the window display normally, but when is a ZIP file with multiples PDF's, the first PDF display correctcly, but starting in the second and on, it doesn't display. show a this error: "Failed to load PDF document".
pdf.php code:
<?php
header ('Content-type: text/html; charset=utf-8');
if(file_exists('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/')+1).'.pdf') && is_file('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/')+1).'.pdf')){
$processo = substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/')+1);
$file = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$processo.'.pdf';
$filename = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$processo.'.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
#readfile($file);
}else{
/////////////////////HERE IS THE PART WHEN IS A ZIP////////////////////////
///////*This part it's only to check if the folder extract exists*/////////
function folder_exist($folder){ $path = realpath($folder); return ($path !== false AND is_dir($path)) ? $path : false; }
chdir('//dsbimrj16/Vinculacao_Cadastro_Gestor/');
$folder = '/'.substr(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'p/')+2), 0, strpos(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'p/')+2), '/')).'/';
if(FALSE !== ($path = folder_exist($folder))){
/////*Here start the part where the code catch the PDF's and display*/////
$pasta = substr(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'p/')+2), 0, strpos(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'p/')+2), '/'));
$processo = substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/')+1);
$file = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$pasta.'/'.$processo.'.pdf';
$filename = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$pasta.'/'.$processo.'.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
#readfile($file);
}else{
die('<h2 style="background-color:#FA5858"><center>Não foi encontrado a inicial do processo. Verifique se o mesmo encontra-se na pasta.</center></h2>');
}
}
?>
What i'm doing wrong ? I've already checked the folder, the file is in and the name and the path is the same that the code are putting to display
Please be aware I am not very familiar with JavaScript and I am doing this to help out a coworker.
I am trying to make an edit to the contact form automatic email replies. The change I am looking to make is when a person sends an email to someone on the website a reply is sent back to the person stating "This is a copy of the following message you sent to WEBSITE PERSON via WEBSITE NAME." The person receiving the email only gets the name of the person that sent it and the message.
I need to add the "This is a copy of the following message you sent to WEBSITE PERSON via WEBSITE NAME" message to the other email because one person is receiving all emails and sending them to the appropriate person. I know, this sounds unreasonable but it is what has been requested.
I found the code in contact.php but I am not entirely sure how to make the change.
This is where the code is getting the portion that I need:
// Check whether email copy function activated
if ($copy_email_activated == true && !empty($data['contact_email_copy']))
{
$copytext = JText::sprintf('COM_CONTACT_COPYTEXT_OF', $contact->name, $sitename);
$copytext .= "\r\n\r\n" . $body;
$copysubject = JText::sprintf('COM_CONTACT_COPYSUBJECT_OF', $subject);
$mail = JFactory::getMailer();
$mail->addRecipient($email);
$mail->addReplyTo($email, $name);
$mail->setSender(array($mailfrom, $fromname));
$mail->setSubject($copysubject);
$mail->setBody($copytext);
$sent = $mail->Send();
}
return $sent;
}
}
And I need the above to work with
// Prepare email body
$prefix = JText::sprintf('COM_CONTACT_ENQUIRY_TEXT', JUri::base());
$body = $prefix . "\n" . $name . ' <' . $email . '>' . "\r\n\r\n" . stripslashes($body);
// Load the custom fields
if (!empty($data['com_fields']) && $fields = FieldsHelper::getFields('com_contact.mail', $contact->email_to, true, $data['com_fields']))
{
$output = FieldsHelper::render(
'com_contact.mail',
'fields.render',
array(
'context' => 'com_contact.mail',
'item' => $contact,
'fields' => $fields,
)
);
if ($output)
{
$body .= "\r\n\r\n" . $output;
}
}
$mail = JFactory::getMailer();
$mail->addRecipient($contact->email_to);
$mail->addReplyTo($email, $name);
$mail->setSender(array($mailfrom, $fromname));
$mail->setSubject($sitename . ': ' . $subject);
$mail->setBody($body);
$sent = $mail->Send();
I thought it would be as simple as copying some code around but I am was very wrong. I knwo there are overrides in Joomla to prevent core code from being touched. As soon as I can get this figured out I can do the override to properly add my changes.
Thank you in advance!
Sorry, i used mobile so it hard to check
// Check whether email copy function activated if ($copy_email_activated == true && !empty($data['contact_email_copy'])) { $copytext = JText::sprintf('COM_CONTACT_COPYTEXT_OF', $contact->name, $sitename); $copytext .= "\r\n\r\n" . $body; $copysubject = JText::sprintf('COM_CONTACT_COPYSUBJECT_OF', $subject);
// Load the custom fields if (!empty($data['com_fields']) && $fields = FieldsHelper::getFields('com_contact.mail', $contact->email_to, true, $data['com_fields'])) { $output = FieldsHelper::render( 'com_contact.mail', 'fields.render', array( 'context' => 'com_contact.mail', 'item' => $contact, 'fields' => $fields, ) ); if ($output) { $copytext .= "\r\n\r\n" . $output; } }
$mail = JFactory::getMailer(); $mail->addRecipient($email); $mail->addReplyTo($email, $name); $mail->setSender(array($mailfrom, $fromname)); $mail->setSubject($copysubject); $mail->setBody($copytext); $sent = $mail->Send(); } return $sent; } }
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);
...
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.
I have a php script that receives parsed data from a javascript application via xmlhttp.
I'm finding that the php script will sometimes stop while it's processing a chunk of data and restart with the same POST data that was sent to it. I thought that maybe the javascript's xmlhttp might be double firing somehow, but I've ruled that out with an inProgress flag as shown below.
function SendPHP(str, callback){
xmlhttp = new XMLHttpRequest();
str = "q=" + encodeURIComponent(str);
xmlhttp.open("POST","sendmail.php", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
inProgress=false;
if(xmlhttp.status == 200){
callback(xmlhttp.responseText);
}
}
};
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
if (inProgress==false){
inProgress=true;
xmlhttp.send(str);
}
else{
writeDisplayConsole("ERROR: xmlhttp fired twice!");
}
}
If the xmlhttp tries to send twice then that error is shown and no further packets will be sent. But that's never the case so the php script must be restarting on it's own.
Bear in mind that it happens at random intervals, not at the same time every time with the same data. What could be causing this to happen?
The php script frequently writes to big text file logs, could that be something to do with it?
Here's the php (but since the error happens at random intervals with the same data, I'm not sure how it could be a problem with the php code):
<?php
writelog("\n*** Sendmail script started ***");
$q = $_POST['q'];
//Split auth code and verify
$pieces = explode("(<!asplit!>)", $q);
$authc=$pieces[0];
$q=$pieces[1];
if ($authc<>"****"){
echo "!Authentification denied.";
writelog ("Authentification denied");
die;
}
writelog ("Authentification accepted");
//Split off packet details
$pieces=explode("(<!psplit!>)", $q);
$tpack=$pieces[0];
$q=$pieces[1];
$pieces=explode("-", $tpack);
$tpacket=$pieces[0];
$ofpacket=$pieces[1];
$totalcontacts=$pieces[2];
//Split contact data from email message
$pieces = explode("(<!dsplit!>)", $q);
$split=$pieces[0];
$q=$pieces[1];
//Assign contacts to array
$contacts = explode ("<!", $split);
$tcount=count($contacts);
$tcount=$tcount-1;
echo "(PACKET ";
echo $tpacket;
echo " OF ";
echo $ofpacket;
echo ")- ";
writelog("(PACKET " . $tpacket . " of " . $ofpacket . ")");
//Killswitch check incase double run
checkKillSwitch("!Startup aborted as Power set to off.",0);
checkKillSwitch("!Aborted, Killswitch set to Kill",1);
file_put_contents('log/killswitch.txt', "on");
echo $tcount;
echo " contacts processing...";
foreach ($contacts as &$value) {
//check killswitch
checkKillSwitch("Killswitch aborted during runtime",1);
$split=explode ("^!", $value);
//Get the contact's details
$firstname= $split[0];
$lastname= $split[1];
$temail = $split[2];
if ($firstname<>""){
$mainmessage=str_replace("[firstname]",$firstname,$q);
$mainmessage=str_replace("[lastname]",$lastname,$mainmessage);
//Split off subject
$pieces = explode("(/subject)", $mainmessage);
$tsubject=$pieces[0];
$mainmessage=$pieces[1];
testLogMail($temail, $tsubject, $mainmessage);
//log progress
$adder=$adder+1;
//For the log, show progress of total (based on 10 per packet change if different)
$tadder = (($tpacket-1)*10)+$adder;
echo ($tadder . ".");
writelog($tadder . " of " . $totalcontacts . " processed >> " . $temail);
sleep(rand(2,20));
}
}
function testLogMail($xaddress, $xsubject, $xmessage){
$tdate=date('d/m/Y H:i:s');
$file = 'log/testmaillog.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Enter email
$towrite="To: ".$xaddress."\n";
$towrite.="Subject: ".$xsubject."\n";
$towrite.="Date: ".$tdate."\n";
$towrite.="...\n";
$towrite.=$xmessage."\n";
$towrite.="___________________________________\n\n";
$current .= $towrite;
// Write the contents back to the file
file_put_contents($file, $current);
}
function writelog($towrite)
{
$tdate=date('d/m/Y H:i:s');
$file = 'log/testlog.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= $towrite." --- ".$tdate."\n";
// Write the contents back to the file
file_put_contents($file, $current);
}
function checkKillSwitch($towrite, $killtype){
if ($killtype==0){
$killswitch = file_get_contents('log/killswitch.txt');
if ($killswitch=="on") {
echo $towrite;
writelog($towrite);
die;
}
}
if ($killtype==1){
$killswitch = file_get_contents('log/killswitch.txt');
if ($killswitch=="kill") {
echo $towrite;
writelog($towrite);
die;
}
}
}
writelog("*** Sendmail script ended ***");
?>