CodeIgniter: Cannot redirect after $this->email->send() - email

i have the following code which sends an email from a posted form:
$this->load->library('email');
$config['charset'] = 'iso-8859-1';
$config['mailtype'] = 'html';
$this->email->initialize($config);
$this->email->from('info#mysite.com', 'Scarabee');
$this->email->to('info#mysite.com');
$this->email->subject('Message via website');
$data['msg'] = nl2br($this->input->post('msg'));
$data['msg'] .= '<br><br><b>Verstuurd door:</b><br>';
if($this->input->post('bedrijf')){
$data['msg'] .= $this->input->post('bedrijf').'<br>';
}
$data['msg'] .= $this->input->post('naam').'<br>';
$data['msg'] .= $this->input->post('adres').' - '.$this->input->post('postcode').', '.$this->input->post('gemeente').'<br>';
$data['msg'] .= $this->input->post('tel').'<br>';
$data['msg'] .= $this->input->post('email');
$message = $this->load->view('email', $data, TRUE);
$this->email->message($message);
if($this->email->send()){
$success = 'Message has been sent';
$this->session->set_flashdata('msg', $success);
redirect('contact/'.$this->input->post('lang'));
}
else{
show_error('Email could not be sent.');
}
Problem: the email gets sent with proper formatting (from the email view template), but the page then goes blank. For instance, if I try to echo out $message just below the $this->email->send() call, nothing shows up. Redirecting, as I’m attempting above, obviously doesn’t work either. Am I missing something? Thanks for any help…
Update
Traced the problem down to a function inside /system/libraries/Email.php (CI's default email library). Commenting out the code inside this function allows the mail to get sent, as well as a proper redirect:
protected function _set_error_message($msg, $val = '')
{
$CI =& get_instance();
$CI->lang->load('email');
if (substr($msg, 0, 5) != 'lang:' || FALSE === ($line = $CI->lang->line(substr($msg, 5))))
{
$this->_debug_msg[] = str_replace('%s', $val, $msg)."<br />";
}
else
{
$this->_debug_msg[] = str_replace('%s', $val, $line)."<br />";
}
}
The line that caused the error is: $CI->lang->load('email');
Go figure...
UPDATE 2: SOLVED
I had this in my controller's construct:
function __construct() {
parent::__construct();
$this->lang = $this->uri->segment(2, 'nl');
}
I guess there was a conflict between $this->lang and the _set_error_message function which also returns a "lang" variable (see var_dump further down).
Solution: changed $this->lang to $this->language, and everything's hunky dory!
Thought I'd post the answer here in case anyone else is ever losing hair with a similar problem :-)

It's likely that an error is occurring when you attempt to send an e-mail which is then killing your script during execution. Check your apache and PHP error logs ( /var/log/apache/ ) and enable full error reporting.

You could, for debugging purposes, try doing this:
...
$this->email->message($message);
$this->email->send();
redirect('contact/'.$this->input->post('lang'));
This should redirect you, regardless of your mail being sent or not (if you still recieve it, you can assume that the redirect would be the next thing that happens).
My own solution looks like this:
...
if ( $this->email->send() )
{
log_message('debug', 'mail library sent mail');
redirect('contact/thankyou');
exit;
}
log_message('error', 'mail library failed to send');
show_error('E-mail could not be send');

$ref2 = $this->input->server('HTTP_REFERER', TRUE);
redirect($ref);
By using the above code you can redirect to the current page itself
and you can set your flash message above the redirect function.

Related

Newbie on Fb messenger Sender_action function

I am under a learning process in chatbot, and kinda new to coding overall ( learning by doing right? )
Trying to execute a messenger function so our chatbot gets the little "writing" bubble for x amount of time before it sends a template. = sender_action_typing_on.
I have tried sleep, await, wait, and so on but the code doesn´t seem to be executed, but the template still shows after the time I chose.
The json is also correct by the documentation from Facebook, and if it get´s executed alone it runs for 20 sek before a timeout.
Code:
if ( $response == "")
{
$jsonData = '{"recipient":{"id":"' . $sender . '"},"message":{"text":"' . $message_to_reply.'"}}';
$jsonDataEncoded = $jsonData;
}
else
if ( $response == "123456")
{
$sender_action_typing_on = '{
"recipient":{
"id":"<PSID>"
},
"sender_action":"Typing_on"
}';
$sender_action_typing_on = str_replace("<PSID>", $sender, $sender_action_typing_on);
$jsonDataEncoded = $sender_action_typing_on;
$velkommenTemplateJSON = str_replace("<PSID>", $sender, $velkommenTemplateJSON);
$jsonDataEncoded = $velkommenTemplateJSON;
}
I have now fixed this issue, this may be very self-explaining for many but for the "lost soul" looking for answers u can see the way i dealed with the problem here:
First i created a new function:
function sendToMessenger($access_token, $sender, $sender_actiontemplateJSON)
{
$content = str_replace("<PSID>", $sender, $sender_actiontemplateJSON);
$opts = array(
'http'=>array(
'method'=>"POST",
'header' => "Content-Type: application/json",
'content' => $content
)
);
$context = stream_context_create($opts);
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token=' . $access_token;
// Open the file using the HTTP headers set above
$file = file_get_contents($url, false, $context);
return $file;
Then i rearranged the way i´m sending template since the template got sent at det end of my code "Sender_action" would always be overwritten, Now with the "SendToMessenger" Function it gets sent right away.
else
if ( $response == "123456")
{
sendToMessenger($access_token, $sender, $sender_actiontemplateJSON);
sleep(1);
sendToMessenger($access_token, $sender, $velkommenTemplateJSON);
}
Now it works like a charm!

Reply-To header not picking the php variable

I am creating a page that sends the response from contact form within mail but reply-to is not working (the variable i am using is having value, but is not added within headers)
here's my code:
<?php
//$uname=$_REQUEST['uname'];
if(isset($_REQUEST['name']))
{
$name=$_REQUEST['name'];
}
if(isset($_REQUEST['email']))
{
$email=$_REQUEST['email'];
}
if(isset($_REQUEST['phone']))
{
$phone=$_REQUEST['phone'];
}
if(isset($_REQUEST['message']))
{
$message=$_REQUEST['message'];
}
// TESTING IF VARIABLES HAVE VALUES
echo "$name $email $phone $message";
// RESULT: TRUE TILL HERE
if($name=="" || $email=="" || $phone=="" || $message=="")
{
header("location:../?inst=invalid");
}
else
{
// ---------------- SEND MAIL FORM ----------------
// send e-mail to ...
$to="mail#example.com";
// Your subject
$subject="$name Contacted you via Contact Form";
// From
$headers = "From: ME <no-reply#example.com>\r\n";
$headers .= 'Reply-To:' . $email . "\r\n";
$headers .= "Return-Path: info#example.com\r\n";
$headers .= "X-Mailer: PHP\n";
$headers .= 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
print $message;
// send email
$sentmail = mail($to,$subject,$message,$headers);
//$sentmail = mail($to1,$subject,$message,$header);
}
// if your email succesfully sent
if($sentmail){
echo "Mail Sent.";
}
else {
header("location:../landing/?status=verification-pending");
}
?>
Now when i checked headers in my gmail, the value for $email doesn't appear in header information, Also no message is received. All I get is a blank message or may be $message is not printing anything like the same case i am facing with reply-to.
please help me a little with this. Thanks in advance.
Check that you have php warnings and notices enabled. When you are echoing out $name, $email, etc you are doing a redirect using headers after that. If your php notices etc aren't turned on, your header redirect will fail due to having already echoed something, and you won't know that you had invalid input. This is part of the reason you shouldn't echo things out during logic, but should store and out put values later.
Actually there was a little mistake with the above code. I mistakenly added = instead of == while comparison.
This line:
if($name=="" || $email="" || $phone="" || $message="")
Should read as:
if($name=="" || $email=="" || $phone=="" || $message=="")
Since = is for equation and not a condition for comparison ==
Fixed it in the Question

Redisplaying a form with fields filled in

I need a bit of help with redisplaying a form.
Basically, currently a user will fill out my contact form, the form and it's contents are passed to my verification page, and if the recaptcha was entered correctly it goes to a Thank You page.
When the recaptcha is entered INCORRECTLY, I want to redisplay the contact form with the fields already filled out. How do I do this? (As you'll see below, it currently goes to google on incorrect captcha)
Here is my verification code. Any help would be great:
<?php require('sbsquared.class.php'); ?>
<?php
require_once('recaptchalib.php');
$privatekey = "myprivatekey";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
header("Location: http://www.google.com"); <--- this is the bit that I want to redisplay the form with fields already filled out.
} else {
$sb = New SBSquared;
$name = $_POST['FullName'];
$post_keys = array_keys($_POST);
$my_db_string = "<table>";
$ip_address = $_SERVER['REMOTE_ADDR'];
foreach($post_keys as $field)
{
if($_POST[$field] != "" && $field != "submit_y" && $field != "submit_x" && $field != "submit_x")
{
$my_db_string .= "<tr><td><b>".$field.":</b></td><td>";
if($field == "Email")
{
$my_db_string .= ''.$_POST['Email'].'';
}
else
{
$my_db_string .= $_POST[$field];
}
$my_db_string .= "</td></tr>";
}
}
$my_db_string .= "<tr><td><b>IP ADDRESS LOGGED: </b></td><td>".$ip_address."</td></tr>";
$my_db_string .= "</table>";
if(get_magic_quotes_gpc() != 1)
{
$my_db_string = addslashes($my_db_string);
$name = addslashes($name);
}
$conn = $sb->openConnection();
$dts = time();
$sql = "INSERT INTO `contact_queries` VALUES ('', '$name', '$my_db_string', 'n/a', 0, $dts)";
$result = mysql_query($sql, $conn) or die(mysql_error());
$content = '<div id="main_middle">';
$content .= '<span class="title">'.$sb->dt('Contact').'</span>
<p>'.$sb->dt('Thank you for your enquiry. We will contact you shortly.').'</p>
</div>';
// admin auto email.
$dts = date("d.m.y h:ia", time());
$admin_content = "New contact query at $dts";
$admin_content .= "\n\n--\n\n \r\n\r\n";
mail("email address", 'NOTIFICATION: new query', $admin_content, 'From: email address');
$FILE=fopen("./log/auto-contact.txt","a");
fwrite($FILE, $admin_content);
fclose($FILE);
echo pageHeader($sb);
echo pageContent($sb, $content);
echo pageFooter($sb);
}
?>
You probably already answered this for yourself, but if not you can set ReCaptcha to validate prior to submitting the form, much the same as HTML5 validation. It just won't let the user submit until the Captcha is correct. Now, I don't know if it will refresh the captcha if it is incorrect but most of the time I see people putting it into an iFrame so it doesn't refresh the page when refreshing the captcha.
As an alternative, you can use sessions to keep the data filled in.

PEAR Mail, Mail_Mime and headers() overwrite

I'm currently working on a reminder PHP Script which will be called via Cronjob once a day in order to inform customers about smth.
Therefore I'm using the PEAR Mail function, combined with Mail_Mime. Firstly the script searches for users in a mysql database. If $num_rows > 0, it's creating a new Mail object and a new Mail_mime object (the code encluded in this posts starts at this point). The problem now appears in the while-loop.
To be exact: The problem is
$mime->headers($headers, true);
As the doc. states, the second argument should overwrite the old headers. However all outgoing mails are sent with the header ($header['To']) from the first user.
I'm really going crazy about this thing... any suggestions?
(Note: However it's sending the correct headers when calling $mime = new Mail_mime() for each user - but it should work with calling it only once and then overwriting the old headers)
Code:
// sql query and if num_rows > 0 ....
require_once('/usr/local/lib/php/Mail.php');
require_once('/usr/local/lib/php/Mail/mime.php');
ob_start();
require_once($inclPath.'/email/head.php');
$head = ob_get_clean();
ob_start();
require_once($inclPath.'/email/foot.php');
$foot = ob_get_clean();
$XY['mail']['params']['driver'] = 'smtp';
$XY['mail']['params']['host'] = 'smtp.XY.at';
$XY['mail']['params']['port'] = 25;
$mail =& Mail::factory('smtp', $XY['mail']['params']);
$headers = array();
$headers['From'] = 'XY <service#XY.at>';
$headers['Subject'] = '=?UTF-8?B?'.base64_encode('Subject').'?=';
$headers['Reply-To'] = 'XY <service#XY.at>';
ob_start();
require_once($inclPath.'/email/templates/files.mail.require-review.php');
$template = ob_get_clean();
$crfl = "\n";
$mime = new Mail_mime($crfl);
while($row = $r->fetch_assoc()){
$html = $head . $template . $foot;
$mime->setHTMLBody($html);
#$to = '=?UTF-8?B?'.base64_encode($row['firstname'].' '.$row['lastname']).'?= <'.$row['email'].'>'; // for testing purpose i'm sending all mails to webmaster#XY.at
$to = '=?UTF-8?B?'.base64_encode($row['firstname'].' '.$row['lastname']).'?= <webmaster#XY.at>';
$headers['To'] = $to; // Sets to in headers to a new
$body = $mime->get(array('head_charset' => 'UTF-8', 'text_charset' => 'UTF-8', 'html_charset' => 'UTF-8'));
$hdrs = $mime->headers($headers, true); // although the second parameters says true, the second, thrid, ... mail still includes the To-header form the first user
$sent = $mail->send($to, $hdrs, $body);
if (PEAR::isError($sent)) {
errlog('error while sending to user_id: '.$row['id']); // personal error function
} else {
// Write log file
}
}
There is no reason to keep the old object and not creating a new one.
Use OOP properly and create new objects - you do not know how they work internally.

Triggering conversion tracking code on form submit

I have a PHP form that mail()s the form data on submit and then if successful returns them to the referring page (in other words keeping them on the same page as the form) and appends ?success=TRUE to the URL.
The question is, how would I implement the AdWords and Yahoo Search Marketing conversion code snippets to trigger only when the form is submitted? For functionality purposes, it is unfortunately not feasible to send them to another page on submit which would have been the easiest way to do it.
The relevant code from the form submit action that mails the results and sends them back to the homepage is below. I have a hunch it might be as simple as outputting the conversion tracking code snippets in the if statement at the end there but I'm not sure if that is correct or the syntax to properly do that.
if ( isset($_POST['sendContactEmail']) )
{
$fname = $_POST['posFName'];
$lname = $_POST['posLName'];
$phone = $_POST['posPhone'];
$email = $_POST['posEmail'];
$note = $_POST['posText'];
$to = $yourEmail;
$subject = $yourSubject;
$message = "From: $fname $lname\n\n Phone: $phone\n\n Email: $email\n\n Note: $note";
$headers = "From: ".cleanPosUrl($_POST['posFName']. " " .$_POST['posLName'])." \r\n";
$headers .= 'To: '.$yourName.' '."\r\n";
$mailit = mail($to,$subject,$message,$headers);
if ( #$mailit ) {
header('Location: '.$referringPage.'?success=true');
}
else {
header('Location: '.$referringPage.'?error=true');
}
}
Outputting it in the if-Statement would be a possibility, but the script you posted adds another way to do it as it redirects to the $referringPage - if the mail was successfully sent. And that's the only event you want to track a conversion.
So edit the code of $referringPage (the page that holds the form fields) and add:
<?php
if($_GET['success'] == 'true') {
echo "...";
}
?>
"..." ofcourse has to be replaced by the Adwords conversion Code Google gave you.
If you add it to your question, I could even add it to my answer.