PHPMailer loop stops if incorrect email address - try-catch

Here is my code to send emails with PHPMailer.
It works seamlesly if mailto address is correct.
But if mailto address is incorrect or doesn't exist, the loop stops and will not deliver the rest of the emails on the database.
I guess that what happens is that $mailer->send() throughs an error if email is incorrect, which makes it jump to the catch and the sending of the email is not registered on the database (don't know why it jumps the update query though). This then loops for ever and nothing really happens.
Any ideas on how to fix?
If mailto address doesn't exist I just want to jump it and keep on with the rest of emails, or maybe, register it as sent = 'no' and keep going with the rest.
//SEND EMAIL
$x = 1;
while ($x > 0) {
$result = $db->query("SELECT * FROM emails WHERE sent = '' AND mailto <> '' ORDER BY id ASC LIMIT 1");
if (mysqli_num_rows($result)==0) {
$x = 0;
} else {
$row = $result->fetch_assoc();
$id = $row["id"];
//Load email data
$mailer->AddAddress($row["mailto"]);
$mailer->Subject = $row["mailsubject"];
$mailer->Body = $row["mailbody"];
try {
//Send email
$mailer->send();
//Register email sent on db
$update = $db->query("UPDATE IGNORE emails SET sent='yes', date=now() WHERE id='$id'");
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mailer->ErrorInfo}";
$mailer->getSMTPInstance()->reset(); //Reset the connection to abort sending this message.
}
//Clear all addresses and attachments for the next iteration
$mailer->clearAddresses();
$mailer->clearAttachments();
}
usleep(100000); //sleep for 0.1 seconds
continue;
}

Ok, solved the problem myself.
In case it helps someone here is the optimised functioning code that will not halt if mailto or mailbcc address is not correct or doesn't exist.
$result = $db->query("SELECT * FROM emails WHERE sent = '' AND mailto <> ''");
foreach ($result as $row) {
$id = $row["id"];
try {
$mailer->addAddress($row['mailto'], $row['mailtoname']);
if (!empty($row["mailbcc"])) {
$mailer->AddBCC($row["mailbcc"]);
}
$mailer->Subject = $row["mailsubject"];
$mailer->Body = $row["mailbody"];
if ($mailer->send()) {
//Register email sent on db
$update = $db->query("UPDATE IGNORE emails SET sent='yes', date=now() WHERE id='$id'");
}
} catch (Exception $e) {
echo "Mailer Error: {$mailer->ErrorInfo}";
//Register that email was not sent so that loop does not stop here
$update = $db->query("UPDATE IGNORE emails SET sent='no' WHERE id='$id'");
//Reset the connection to abort sending this message. The loop will continue trying to send to the rest of the list
$mailer->getSMTPInstance()->reset();
}
//Clear all addresses and attachments for the next iteration
$mailer->clearAddresses();
$mailer->clearAttachments();
usleep(100000); //sleep for 0.1 seconds
continue;
}

Related

Getting "Webpage" Redirected You Too Many Times Error. Can't Seem To Figure Out Why

I'm having issues with this error message popping upon user login. From what I've gathered, I think there is an issue with the following code since this is the page on which it stops and gives me this error. This code is at the beginning of the page they see once logged in.
It first verifies the user is logged in and that the correct sessions are set. Then it pulls the additional info from the database and verifies that the user has the correct level of permission. If so, it allows them to access the page. If not it redirects them to the login page.
<?php
require_once 'account-management/reset-password-script.php';
$email = $_SESSION['email'];
$password = $_SESSION['password'];
if($email != false && $password != false){
$sql = "SELECT * FROM administration WHERE email = '$email'";
$run_Sql = mysqli_query($conn, $sql);
if($run_Sql){
$fetch_info = mysqli_fetch_assoc($run_Sql);
$name = $fetch_info['name'];
$rank = $fetch_info['rank'];
$job_title = $fetch_info['job_title'];
$user_id = $fetch_info['id'];
if($rank == "Admin" || $rank == "Moderator" || $rank == "Editor"){
header('Location: stats.php');
}
}
}else{
header('Location: login.php');
}
?>
Here is the code that logs the user on.
It verifies the email, password, and permission settings, and then brings them to the stats page if the info checks out.
session_start();
require 'db_connect.php';
$email = "";
$errors = array();
if(isset($_POST['login'])){
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$check_email = "SELECT * FROM administration WHERE email = '$email'";
$res = mysqli_query($conn, $check_email);
if(mysqli_num_rows($res) > 0){
$fetch = mysqli_fetch_assoc($res);
$fetch_pass = $fetch['password'];
if(password_verify($password, $fetch_pass)){
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
$rank = $fetch['rank'];
if($rank == "Admin" || $rank == "Moderator" || $rank == "Editor"){
header('location: stats.php');
}else{
$info = "It's looks like you don't have this permission.";
}
}else{
$errors['email'] = "Incorrect email or password!";
}
}else{
$errors['email'] = "<div id='alert-messages-normal'>It looks like you're not yet a member! Click on the sidebar link to signup.<br/></div>";
}
}
Again, the issue is that once it passes the login face, it goes to the stats page which is locked to non-users. It then loads for a few seconds and then just displays the error that it redirected too many times. The goal is for it to just stay on the users-only page.
I've tried rewriting the code a few times and cleared the browser cache several times. I can't seem to find the issue. I feel like the error is definitely within the code to verify the user is logged in before displaying the content. Something is making it loop between the login page and the user-only page, and my eyes can't seem to figure it out.

Helping me understand session api Gatling

I am new to gatling
I am trying to loop on json response, find the country code that I am looking for and take the id coressponding the that coutry code.
Sample algorithm:
list.foreach( value => { if (value.coutrycode == "PL") then store value.id })
on Gatling:
def getOffer() = {
exec(
http("GET /offer")
.get("/offer")
.check(status.is(Constant.httpOk))
.check((bodyString.exists),
jsonPath("$[*]").ofType[Map[String,Any]].findAll.saveAs("offerList")))
.foreach("${offerList}", "item"){
exec(session => {
val itemMap = session("item").as[Map[String,Any]]
val countryCodeId = itemMap("countryCode")
println("****" + countryCodeId)
// => print all the country code on the list
if (countryCodeId =="PL"){ // if statement condition
println("*************"+ itemMap("offerd")); // print the id eg : "23"
session.set("offerId", itemMap("offerId")); // set the id on the session
}
println("$$$$$$$$$$$$$$" + session("offerId")) // verify that th session contains the offerId but is not
session
})
}
}
When I try to print the session("offerId"), it's print "item" and not the offerId.
I looked on the documentation but I didn't understand the behaviour. Could you please explain it to me ?
It's all in the documentation.
Session instances are immutable!
Why is that so? Because Sessions are messages that are dealt with in a
multi-threaded concurrent way, so immutability is the best way to deal
with state without relying on synchronization and blocking.
A very common pitfall is to forget that set and setAll actually return
new instances.
val session: Session = ???
// wrong usage
session.set("foo", "FOO") // wrong: the result of this set call is just discarded
session.set("bar", "BAR")
// proper usage
session.set("foo", "FOO").set("bar", "BAR")
So what you want is:
val newSession =
if (countryCodeId =="PL"){ // if statement condition
println("*************"+ itemMap("offerd")); // print the id eg : "23"
session.set("offerId", itemMap("offerId")); // set the id on the session
} else {
session
}
// verify that the session contains the offerId
println("$$$$$$$$$$$$$$" + newSession("offerId").as[String])
newSession

PHP mailer and FPDF attachment with loop - script stops after first run

I'm running a following script to generate and send email. The email body is generated in a while loop (content differs) - it works fine. But now I have tried to include a script to generate PDF attachment (via FPDF library), in each iteration the attachment is different.
Problem is: the loop runs just once, for the first case and after it stops. Thank you for your commnents in advance.
My code:
<?
$mail = new PHPMailer();
$mail->SMTPDebug = 1;
$mail->isSMTP();
$mail->addReplyTo('');
$mail->isHTML(true);
$mail->Subject = "";
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->CharSet = 'utf-8';
$mail->setFrom('');
while(($data=MySQL_Fetch_Array($vysl))!=NULL) {
require_once('invoicetopdf.php');
$message="";
$mail->AddStringAttachment($invoice, 'Invoice.pdf', 'base64', 'application/pdf');
$mail->Username = "";
$mail->Password = "";
$mail->addAddress($to);
$mail->Body = $message;
if (!$mail->send()) {echo "Mailer Error: " . $mail->ErrorInfo;}
else {
$mail->clearAddresses();
$mail->ClearAllRecipients();
$mail->clearAttachments();
echo "Ok";
}
} //while
//invoicetopdf.php:
$data = MySQL_Fetch_Array($vysl);
require_once('../knihovny/pdf/fpdf.php');
$pdf = new PDF();
$pdf->.....;
$invoice=$pdf->Output('S');
?>
That's a bit of an odd way to run that code repeatedly. I would define a function in your invoicetopdf.php file, load it at the top of your script, and then call the function inside the loop to get the PDF data. You're also calling mysql_fetch_array twice - once in the while loop, once in the function, meaning half your data will be going astray.
require_once('invoicetopdf.php');
while(($data=MySQL_Fetch_Array($vysl))!=NULL) {
$message="";
$mail->AddStringAttachment(generatePDF($data), 'Invoice.pdf', 'base64', 'application/pdf');
...
//invoicetopdf.php:
require_once('../knihovny/pdf/fpdf.php');
function generatePDF($data) {
$pdf = new PDF();
$pdf->.....;
return $invoice=$pdf->Output('S');
}
I also recommend moving the Username and Password out of the loop, and you probably don't need to call clearAllRecipients(); clearAddresses() is enough.
Setting SMTPDebug = 2 will let you see more of what's happening in SMTP land.
Now it works: the main problem was a mixing a class and functions together. See:Multiple PDFs in Loop with FPDF
Thank you guys!

joomla - Storing user parameters in custom component issue

Hi for my custom component I need to set some custom parameters for joomla user for membership for checking if the user ni trial period or not and it can be change from the component admin panel for specific user.
The problem arises while retrieving the parameter. I think it is stored in cookie and it isn^t updated. I wrote the code like that to check it.
$user = JFactory::getUser(JRequest::getVar('id','0'));
echo $user->getParam('trialPeriod','0');
to save the value I am useing JHTML booleanlist.
$user->setParam('trialPeriod',$data['trialPeriod']);
$user->save();
Then is stores the value in joomla users table in the row of that user with column of params as;
{"trialPeriod":"0"}
in this situation it echoes the value as 0. Then I am changin the state of trialPeriod var as 1 and storing in db it updates the db as;
{"trialPeriod":"1"}
After all I am refreshing the page where the value is prompt the the screen the the value remains still the same as 0;
To clarify;
First of all there is no problem with saving the param it is changed properly. The problem is retrieving the changed one. The releated piece of code is following;
$user = JFactory::getUser();
$doc = JFactory::getDocument();
if($user->getParam('trialPeriod',0) == 0){
$ed = JFactory::getDate($obj->expirationDate);//obj is user from custom table and there is no problem with getting it.
$isTrialEnd = FALSE;
}else{
$ed = JFactory::getDate($user->getParam('trialExp',0));
$isTrialEnd = TRUE;
}
if($isTrialEnd){
//do something else
}else{
echo $user->getParam('trialPeriod','0');
}
actually big part of the code is unneccessary to explain it but you will get the idea.
What is the solution for this?
Editted.
$app = JFactory::getApplication();
$config = JFactory::getConfig();
$db = $this->getDbo();
$isNew = empty($data['uid']) ? true : false;
$params = JComponentHelper::getParams('com_dratransport');
if($isNew){
// Initialise the table with JUser.
$user = new JUser;
// Prepare the data for the user object.
$username = self::getCreatedUserName($data['type']);
$data['username'] = !empty($data['username']) ? $data['username'] : $username;
$data['password'] = $data['password1'];
$useractivation = $params->get('useractivation');
// Check if the user needs to activate their account.
if (($useractivation == 1) || ($useractivation == 2)) {
$data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword());
$data['block'] = 1;
}
}else{
$user = JFactory::getUser($data['uid']);
$data['password'] = $data['password1'];
}
$membership = DraTransportHelperArrays::membershipCFG();
$membership = $membership[$data['membership']];
if($data['membership'] == 4)
$data['groups'] = array($params->get('new_usertype',2),$params->get($membership,2));
else
$data['groups'] = array($params->get($membership,2));
$data['name'] = $data['companyName'];
$user->setParam('trialPeriod',$data['trialPeriod']);
// Bind the data.
if (!$user->bind($data)) {
$this->setError(JText::sprintf('COM_USERS_REGISTRATION_BIND_FAILED', $user->getError()));
return false;
}
// Load the users plugin group.
JPluginHelper::importPlugin('user');
// Store the data.
if (!$user->save()) {
$app->enqueuemessage($user->getError());
$this->setError(JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED', $user->getError()));
return false;
}
this piece of code is for storing the data releated with the users table.
Turns out this was the fact that Joomla stores the JUser instance in the session that caused the problem.
When changing a user's parameters from the back-end, the changes are not reflected in that user's session, until she logs out and back in again.
We could not find an easy option to modify anther user's active session, so we resorted to the use of a plugin that refreshes the JUser instance in the logged-in users' session, something like the following:
$user = JFactory::getUser();
$session = JFactory::getSession();
if(!$user->guest) {
$session->set('user', new JUser($user->id));
}
(reference: here).

C# login message warning

Well im here because i have a problem. i have code that was created a while ago. my code is working properly when i a user type the correct username and password. so my problem is when a user insert wrong username and password error message wont show. Here is my code:
MyDs.Clear();
MyDa.SelectCommand = Conn.CreateCommand();
MyDa.SelectCommand.CommandText =
"select * from PersonalName where Firstname=#first and Lastname=#last";
MyDa.SelectCommand.CommandType = CommandType.Text;
MyDa.SelectCommand.Parameters.Add("#first", DbType.String, 25, "Firstname").Value = textbox_Username.Text;
MyDa.SelectCommand.Parameters.Add("#last", DbType.String, 25, "Lastname").Value = textbox_Password.Text;
MyDa.Fill(MyDs);
foreach (DataRow item in MyDs.Tables[0].Rows)
{
if (textbox_Username.Text != item[1].ToString() || textbox_Password.Text != item[3].ToString())
{
MessageBox.Show("not connected");
}
else
{
MessageBox.Show("Connected");
}
}
Anyone can tell me what is the problem with this code?
Your dataset will be empty if they put in the wrong username. This will be closer to what you want:
if (MyDs.Tables[0].Rows.Count > 0)
{
// you don't need to check username, the SQL query took care of that
if (textbox_Password.Text == item[3].ToString())
MessageBox.Show("Connected.");
else
MessageBox.Show("Failed."); // wrong password
}
else
MessageBox.Show("Failed."); // no such user
if the query returns no records becasue firast and last name aren't present, foreach doesn't execute nothing happens...
You need to test for myDa being empty as well, your code only works for checking valid users.

Resources