Too many redirects sending email via phpmailer - php

I have a table in the db that queues and stores all the mails that are sent through a script that inserts data into this table.
Another script in php manages the sending, given the high number of emails, to avoid spamming it sends them in groups of 50.
it repeats the loop until all the tuples have been sent.
(there is a column for each tuple with queued or sent set)
The problem is the following:
Given, precisely, the high number of submissions, at a certain point the script crashes (chrome) with the error "ERR_TOO_MANY_REDIRECTS".
How can i resolve?
<?php
require_once '../dbh.inc.php';
include_once '../functions.php';
error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('Etc/UTC');
require '../PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail-> isSMTP();
$mail->Host = 'smtps.*****.it';
$mail->SMTPDebug = 0;
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->SMTPAutoTLS = false;
$mail->SMTPSecure = 'ssl';
$mail->Username = 'intranet#*****.it';
$mail->Password = '*****';
$mail->Priority = '1';
$mail->setFrom('intranet#*****.it', '*****');
$process_count = 50;
$sql = "SELECT * FROM `email_queue` WHERE `status` = 'queued' AND `do_not_send_before` < '" .strtotime("now") ."'
ORDER BY `submission_date`, `priority` ASC LIMIT $process_count ";
$result = mysqli_query($conn, $sql);
foreach ($result as $row) {
$mail->addAddress($row['recipient']);
$mail->addReplyTo($row['reply_to']);
$mail->IsHTML(true);
$mail->CharSet = "UTF-8";
$mail->Subject = $row['subject'];
$mail->msgHTML($row['message']);
$mail->AltBody = "";
$file1 = $row['file1'];
$file2 = $row['file2'];
$file3 = $row['file3'];
$file4 = $row['file4'];
$file5 = $row['file5'];
$filepath = '/web/htdocs/www.*****.it/home/it/intranet/uploads/mails/';
if (!empty($file1)) {
$file1 = $filepath.$file1;
$mail->AddAttachment($file1);
}
if (!empty($file2)) {
$file2 = $filepath.$file2;
$mail->AddAttachment($file2);
}
if (!empty($file3)) {
$file3 = $filepath.$file3;
$mail->AddAttachment($file3);
}
if (!empty($file4)) {
$file4 = $filepath.$file4;
$mail->AddAttachment($file4);
}
if (!empty($file5)) {
$file5 = $filepath.$file5;
$mail->AddAttachment($file5);
}
if (!$mail->send()) {
echo "Mailer Error (" . str_replace("#", "#", $row["recipient"]) . ') ' . $mail->ErrorInfo . '<br />';
break; //Abandon sending
} else {
$now = strtotime("now");
//echo "Messaggio inviato a :" . ' (' . str_replace("#", "#", $row['recipient']) . ')<br />';
//Mark it as sent in the DB
$sql1 = "UPDATE `email_queue` SET `status` = 'sent', `sent_date` = '$now' WHERE `id` = '" . $row['id'] . "'";
$result = mysqli_query($conn, $sql1);
if ($result) {
echo "Mail Inviata correttamente a: (" . str_replace("#", "#", $row["recipient"]) . ') <br />';
} else {
echo "error $sql1 </br>";
}
}
// Clear all addresses and attachments for next loop
$mail->clearAddresses();
$mail->clearAttachments();
}
$sql2 = "SELECT COUNT(*) AS count FROM `email_queue` WHERE `status` = 'queued';";
$result2 = mysqli_query($conn, $sql2);
$row2 = mysqli_fetch_assoc($result2);
$count = $row2['count'];
echo "$count";
if ($count > 0) {
header('Location: '.$_SERVER['PHP_SELF']);
} else {
header('Location:' . $USER_LOCATION . "index.php?emails=success");
}
?>

At the end of script, you have else-if condition which always results in a redirect. If the count of rows is bigger than 0, you redirect it to the same script, without end. It results in a never-ending loop of redirects.
Just do not redirect in this case, or redirect to another script that won't redirect to another (or the same) script again.
pseudo code:
if ($count > 0) {
// do something here instead of redirect
} else {
header('Location:' . $USER_LOCATION . "index.php?emails=success");
}

header('Location: '.$_SERVER['PHP_SELF']); always redirects to same URL and there server sees infinite redirect, that's why TOO_MANY_REDIRECTS.
Do not use re-directs here. Use loop.
do {
$count = $this->getCount();
if ($count > 0) {
$this->processEmails();
}
} while ($count > 0);
Note that this process may be executed longer than 30s and it would time out your ordinary browser request. Use it as CLI command

Related

Attach Database Backup file in E-Mail send not working

I am using following code to take backup of my mysql database.
With this code, a file is created and get saved in same folder where this script is kept. It is working perfectly.
I am trying to email this file using phpmailer. But I am stucked as no file is getting attached to receiving email. (email is delivered without attached file...)
Basic code is taken from https://write.corbpie.com/php-pdo-mysql-backup-script-with-compression-option/
Help is appreciated... and thank you in advanced...
Backup creating code part is as follows :
<?php
include_once("../../include/mysqli_constants.php");
require("../../PHPMailer/class.phpmailer.php");
$db_server = constant('HST');
$db_name = constant('DBN');
$db_user = constant('USR');
$db_pass = constant('PWD');
$site_url = constant('FILEROOT');
$from_email = constant('FROMEMAIL');
$from_name = constant('FROMNAME');
$mail_to1 = 'mypersonal#gmail.com';
$mail_to1_name = 'Dr Manish Joshi';
$mail_to2 = '';
$mail_to2_name = '';
$save_dir = './';
$file_name_prefix = 'my_website_';
$date = strtolower(date('d_F_Y_H_i_s_A'));
/* Do NOT EDIT BELOW */
$backup_config = array(
'DB_HOST' => $db_server,////Database hostname
'DB_NAME' => $db_name,//Database name to backup
'DB_USERNAME' => $db_user,//Database account username
'DB_PASSWORD' => $db_pass,//Database account password
'INCLUDE_DROP_TABLE' => false,//Include DROP TABLE IF EXISTS
'SAVE_DIR' => '',//Folder to save file in
'SAVE_AS' => $file_name_prefix,//Prepend filename
'APPEND_DATE_FORMAT' => 'Y_m_d_H_i_s',//Append date to file name
'TIMEZONE' => 'Asia/Kolkata',//Timezone for date format
'COMPRESS' => true,//Compress into gz otherwise keep as .sql
);
echo backupDB($backup_config);
Email sending part is as follows :
$mail = new PHPMailer();
$mail->IsHTML(true);
$mail->Host = constant('EMAILHOST');
$mail->AddAddress(''.$mail_to1.'', ''.$mail_to1_name.'');
$mail->IsSMTP();
$mail->SMTPAuth = constant('SMTPAuth');
$mail->SMTPSecure = 'tls';
$mail->Mailer = "smtp";
$mail->SMTPDebug = constant('SMTPDEBUG');
$mail->Username = constant('SMTPUSERNAME');
$mail->Password = constant('SMTPPASSWORD');
$mail->Port = 587;
$mail->From = constant('FROMEMAIL');
$mail->FromName = constant('FROMNAME');
$mail->WordWrap = 50;
$mail->Subject = '['.$from_name.'] Cron Backup MySQL On - ' . $date;
$mail->Body = $save_string.' File is attached via cron';
$mail->AddAttachment($save_string);
if (!$mail->AddAttachment($save_string)) {
echo 'Erreur : ' . $mail->ErrorInfo . "\n";
$mail->Body .= "\n" . 'Erreur : ' . $mail->ErrorInfo;
}
if (!$mail->Send()){
echo 'Message could not be sent. <p>';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';
Function to create database backup is as follows and it is working OK and creating db backup and saving file in folder.
/* FUNCTION Starts */
function backupDB(array $config): string {
$db = new PDO("mysql:host={$config['DB_HOST']};dbname={$config['DB_NAME']}; charset=utf8", $config['DB_USERNAME'], $config['DB_PASSWORD']);
$db->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_NATURAL);
date_default_timezone_set($config['TIMEZONE']);
$do_compress = $config['COMPRESS'];
if ($do_compress) {
$save_string = $config['SAVE_AS'] . $config['SAVE_DIR'] . date($config['APPEND_DATE_FORMAT']) . '.sql.gz';
$zp = gzopen($save_string, "a9");
} else {
$save_string = $config['SAVE_AS'] . $config['SAVE_DIR'] . date($config['APPEND_DATE_FORMAT']) . '.sql';
$handle = fopen($save_string, 'a+');
}
//array of all database field types which just take numbers
$numtypes = array('tinyint', 'smallint', 'mediumint', 'int', 'bigint', 'float', 'double', 'decimal', 'real');
$return = "";
$return .= "CREATE DATABASE `{$config['DB_NAME']}`;\n";
$return .= "USE `{$config['DB_NAME']}`;\n";
//get all tables
$pstm1 = $db->query('SHOW TABLES');
while ($row = $pstm1->fetch(PDO::FETCH_NUM)) {
$tables[] = $row[0];
}
//cycle through the table(s)
foreach ($tables as $table) {
$result = $db->query("SELECT * FROM $table");
$num_fields = $result->columnCount();
$num_rows = $result->rowCount();
if ($config['INCLUDE_DROP_TABLE']) {
$return .= 'DROP TABLE IF EXISTS `' . $table . '`;';
}
//table structure
$pstm2 = $db->query("SHOW CREATE TABLE $table");
$row2 = $pstm2->fetch(PDO::FETCH_NUM);
$ifnotexists = str_replace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS', $row2[1]);
$return .= "\n\n" . $ifnotexists . ";\n\n";
if ($do_compress) {
gzwrite($zp, $return);
} else {
fwrite($handle, $return);
}
$return = "";
//insert values
if ($num_rows) {
$return = 'INSERT INTO `' . $table . '` (';
$pstm3 = $db->query("SHOW COLUMNS FROM $table");
$count = 0;
$type = array();
while ($rows = $pstm3->fetch(PDO::FETCH_NUM)) {
if (stripos($rows[1], '(')) {
$type[$table][] = stristr($rows[1], '(', true);
} else {
$type[$table][] = $rows[1];
}
$return .= "`" . $rows[0] . "`";
$count++;
if ($count < ($pstm3->rowCount())) {
$return .= ", ";
}
}
$return .= ")" . ' VALUES';
if ($do_compress) {
gzwrite($zp, $return);
} else {
fwrite($handle, $return);
}
$return = "";
}
$counter = 0;
while ($row = $result->fetch(PDO::FETCH_NUM)) {
$return = "\n\t(";
for ($j = 0; $j < $num_fields; $j++) {
if (isset($row[$j])) {
//if number, take away "". else leave as string
if ((in_array($type[$table][$j], $numtypes)) && (!empty($row[$j]))) {
$return .= $row[$j];
} else {
$return .= $db->quote($row[$j]);
}
} else {
$return .= 'NULL';
}
if ($j < ($num_fields - 1)) {
$return .= ',';
}
}
$counter++;
if ($counter < ($result->rowCount())) {
$return .= "),";
} else {
$return .= ");";
}
if ($do_compress) {
gzwrite($zp, $return);
} else {
fwrite($handle, $return);
}
$return = "";
}
$return = "\n\n-- ------------------------------------------------ \n\n";
if ($do_compress) {
gzwrite($zp, $return);
} else {
fwrite($handle, $return);
}
$return = "";
}
$error1 = $pstm2->errorInfo();
$error2 = $pstm3->errorInfo();
$error3 = $result->errorInfo();
echo $error1[2];
echo $error2[2];
echo $error3[2];
if ($do_compress) {
gzclose($zp);
} else {
fclose($handle);
}
return "{$config['DB_NAME']} saved as $save_string";
}
?>
I have edited this code and now it is working...
Edited code kept on github...
https://github.com/vaidyamanishjoshi/db-backup-with-pdo-and-email-it

cannot send the email while attaching the excel sheet in php

When i am trying to send an excel sheet as attachment in php, it shows that cannot access the file. But if i am commenting the attachment part, the mail will send perfectly. When i am trying to download the sheet it works perfectly.
Will anyone guide me how can i fix this problem?
Thank you
$select="select * from tablename";
$export = mysql_query($select);
$fields = mysql_num_fields($export);
$csv_output = '';
$data='';
for ($i = 0; $i < $fields; $i++) {
$csv_output .= mysql_field_name($export, $i) . "\t";
}
while ($row = mysql_fetch_row($export)) {
$line = '';
foreach ($row as $value) {
if ((!isset($value)) OR ($value == "")) {
$value = "NULL\t";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim($line) . "\n";
}
$data = str_replace("\r", "", $data);
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username ='xxxx#gmail.com';
$mail->Password = 'password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('xxxxx#gmail.com', 'name');
$mail->addAddress('xxxxx#gmail.com', 'name');
$mail->addAttachment($csv_output . "\n" . $data);
$mail->isHTML(true);
$mail->Subject = 'Report';
$mail->Body = '<b>Please find the attachment of the Report</b>';
$mail->AltBody = 'Please find the attachement of the Report';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
addAttachment expects a path to a file, not raw attachment content. Easiest fix would be to store your attachment content to a temporary file and then give the path to that.
So instead of:
$mail->addAttachment($csv_output . "\n" . $data);
You could do something like:
$report_filename = date('Y-m-d-his-').'-report.txt';
file_put_contents($report_filename, $csv_output . "\n" . $data);
$mail->addAttachment($report_filename);
//....
$mail->send();
unlink($report_filename);

Send learners reminder email and admin

Below code should send email to learners but the code is giving me error:
"Fatal error: Call to undefined method mysqli_result::fetch() in /home/train4/public_html/hocotest/cron-email-expire-1.php on line 46"
I replaced fetch(PDO::FETCH_OBJ) with fetch_object() then the file runs fine no error but the learners are not getting emails.
there is 2 parts of this email,
1. it will send email to learners
2. Send email to admin that to whom the system have system have sent the email.
the second part run fine, admin get the email but there is no info to whom the system have sent emails to, as part 1 is not working.
I tried running the script without array, so the system send 1 email for each course, if the learners are enrolled in 7 courses and not completed 5 courses then they will get 5 emails.. it work fine. but i want to send only one email with all not completed course details.
<?php
include 'db.php';
function check_emailaddress($email) {
// First, we check that there is one # symbol, and that the lengths are right
if (!ereg("^[^#]{1,64}#[^#]{1,255}$", $email))
{
// Email invalid because wrong number of characters in one section, or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++)
{
if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i]))
{
return false;
}
}
if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) // Check if domain is IP. If not, it should be valid domain name
{
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2)
{
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++)
{
if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i]))
{
return false;
}
}
}
return true;
}
$extraParam = "";
if (isset($_GET["ex"]) ) {
$extraParam = $_GET["ex"]."---";
}
//get system sender email address from settings table
$srs = $db->query("SELECT adminemail, systememail FROM tbl07systemsettings");
$srow = $srs->fetch(PDO::FETCH_OBJ);
$from = $srow->systememail; //"From: info#visiondesigngroup.ca\r\n";
$email_from = "From: $from\r\n";
$admin_email = "toralhc6#gmail.com";
$email_to = "" ;//"respite#safeguards-training.net";
$tempsql = "SELECT a06subject, a06templatebody, usetemplate FROM tbl06emailtemplates WHERE a06name = 'autoreminder'";
$rs = $db->query($tempsql);
$rowemail = $rs->fetch(PDO::FETCH_OBJ);
$usetemplate = $rowemail->usetemplate;
if ($usetemplate == 0) exit; // not send email if course reminder email template was set not to send email *************
$email_subject = $rowemail->a06subject;
//$from = "From: info#visiondesigngroup.ca\r\n";
$eb = $rowemail->a06templatebody;
$strSQL_expire = "SELECT * FROM tbl01user, tbl04usercourses, tbl03courses
WHERE a01User=a04UserId AND a03CourseId=a04CourseId
AND DATEDIFF(CURDATE(),a04StartDate) > 0 AND a04Completion=0
AND a01UserRoll=0 AND a01Status=1 AND a04Status=1";
$query = $db->query($strSQL_expire) or die ("Error querying database.<br>$strSQL_expire");
$nofinish = array();
$course = "";
$pre_email = "";
$pre_fn = "";
$n = 0;
while($email_row=$query->fetch(PDO::FETCH_OBJ)){
$fn = $email_row->a01FirstName;
$email = $email_row->a01Email;
$password = $email_row->a002password;
if ($pre_email == $email){
$course .= "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}else{
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
$course = "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}
}
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
array_shift($nofinish);
set_time_limit(600);
$eb1 = nl2br($eb);
$i = 0;
foreach($nofinish as $no){
$email_from = $from;
$email_address = $no['email'];
// $email_address = "lyan3000#gmail.com";
// if ($i++ >= 4) exit;
// need to comment the above two lines before go live***********************************************
$email_subject = "Course Completion Reminder";
$top = "<div style='font-family:Arial'>";
$top .= "<div style='background-color:#045FB4; color:white;width:100%;padding:10px 10px;'><h1>Service Centre</h1></div>";
$variable = array(
'{$firstname}' => $no['firstname'],
'{$course}' => $no['courses'],
'{$password}'=> $no['password'],
'{$email}'=> $no['email']
);
$email_body = strtr($eb1, $variable);
$bottom = "<p><img src='cid:logoimg'></p>";
$bottom .="<div style='background-color:#045FB4; height:25px;width:100%'> </div></div>";
$email_message = $top . $email_body . $bottom;
/*
echo $email_from . "<br>";
echo $email_address . "<br>";
echo $email_subject . "<br>";
echo $email_message;
echo "<hr>";
*/
if (mail($email_address, $email_subject, $email_message, $email_from))
{
//echo "Reminder email sent to: " . $no['firstname'] . "<br>";
echo "Yes. <br>";
}else{
//echo "Sorry, There is a mail server error. Please try it again later " . $no['firstname'] . "<br>";
echo "No. <br>";
}
}
$file_name = "record_for_cron_expire_email.txt";
$tz = 'EST';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
$date = $dt->format('Y-m-d h:i:s A');
$text = "This script runs on $date " . PHP_EOL;
file_put_contents ( $file_name , $text, FILE_APPEND);
//send summurized email to admin
$sql = "SELECT a06subject, a06templatebody FROM tbl06emailtemplates WHERE a06name = 'remindertoadmin'";
$rs = $db->query($sql);
$row = $rs->fetch_object();
$email_subject = $row->a06subject;
//$from = "From: $email_from\r\n";
$date = date('Y-m-d');
$eb = $row->a06templatebody;
$variable = array(
'{$learnerCourse}' => $learnercourse,
'{$date}' => $date
);
$email_body = strtr($eb, $variable);
mail($admin_email, $email_subject, $email_body, $email_from);
//SET inactive all expired courses
$expiredRightNow = date("Y-m-d");
$strSQL_setExpire = "UPDATE tbl04usercourses
SET a04Status = 0
WHERE a04ExpirationDate <= '$expiredRightNow'
AND a04Completion = 0";
$query = $db->query($strSQL_setExpire) or die ("Error querying database.<br>$strSQL_setExpire");
?>
mysqli_result::fetch_all() requires MySQL Native Driver (mysqlnd).
chances are you might be missing it.
have a look at this posts, that might help you.
mysqli fetch_all() not a valid function?
below is the minimal code I can think of:
$strSQL_expire = "SELECT * FROM tbl01user, tbl04usercourses, tbl03courses
WHERE a01User=a04UserId AND a03CourseId=a04CourseId
AND DATEDIFF(CURDATE(),a04StartDate) > 0 AND a04Completion=0
AND a01UserRoll=0 AND a01Status=1 AND a04Status=1";
$query = $db->query($strSQL_expire) or die ("Error querying database.<br>$strSQL_expire");
$nofinish = array();
$course = "";
$pre_email = "";
$pre_fn = "";
$n = 0;
while($email_row=$query->fetch(PDO::FETCH_OBJ)){
$fn = $email_row->a01FirstName;
$email = $email_row->a01Email;
$password = $email_row->a002password;
if ($pre_email == $email){
$course .= "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}else{
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
$course = "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}
}
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
array_shift($nofinish);
set_time_limit(600);
$eb1 = nl2br($eb);
$i = 0;
foreach($nofinish as $no){
$email_from = $from;
$email_address = $no['email'];
$email_subject = "Course Completion Reminder";
$top = "<div style='font-family:Arial'>";
$top .= "<div style='background-color:#045FB4; color:white;width:100%;padding:10px 10px;'><h1>Service Centre</h1></div>";
$variable = array(
'{$firstname}' => $no['firstname'],
'{$course}' => $no['courses'],
'{$password}'=> $no['password'],
'{$email}'=> $no['email']
);
$email_body = strtr($eb1, $variable);
$bottom = "<p><img src='cid:logoimg'></p>";
$bottom .="<div style='background-color:#045FB4; height:25px;width:100%'> </div></div>";
$email_message = $top . $email_body . $bottom;
if (mail($email_address, $email_subject, $email_message, $email_from))
{
echo "Yes. <br>";
}else{
echo "No. <br>";
}
}

Why is this code returning a line break before the echo?

So I have this login php script that I am using and it works fine on one server (returns "success" || "invalid login") and then this other server it breaks because it returns a line break and then "success" or "invalid login"
My guess is a php.ini setting. I am just not sure which one.
<?php
include("../config.php");
include("../connect.php");
$adminCheck = mysql_query("SELECT * FROM admins WHERE username = '" . mysql_real_escape_string($_POST['username']) . "' AND password = '" . mysql_real_escape_string($_POST['password']) . "'");
if (mysql_num_rows($adminCheck) == 1)
{
$result = mysql_fetch_array($adminCheck);
$_SESSION['user']['level'] = "admin";
$_SESSION['user']['userid'] = $result['id'];
$_SESSION['user']['username'] = $result['username'];
echo "success";
}
else
{
$clientCheck = mysql_query("SELECT * FROM clients WHERE username = '" . mysql_real_escape_string($_POST['username']) . "' AND password = '" . mysql_real_escape_string($_POST['password']) . "'");
if (mysql_num_rows($clientCheck) == 1)
{
$result = mysql_fetch_array($clientCheck);
$_SESSION['user']['level'] = "client";
$_SESSION['user']['userid'] = $result['id'];
$_SESSION['user']['username'] = $result['username'];
$_SESSION['user']['client'] = $result['client'];
echo "success";
}
else
{
echo "invalid login";
}
}
?>
I'd bet you a coke that connect.php or config.php contain a \n (or \r\n) before or after their <?php ?> parts.
This is most likely due to your includes. The code you posted has no reason to have one, and there is no php.ini setting that I'm aware of to add such.
Post your config and connect (with username/pw hidden) for us to help further.
The code displayed does not indicate the occurrence of a line-break.
On a side note since you are only outputting one value from your booleans then you could initialize a variable to hold the response and then only echo the response once:
<?php
include("../config.php");
include("../connect.php");
$response = 'success';
$adminCheck = mysql_query("SELECT * FROM admins WHERE username = '" . mysql_real_escape_string($_POST['username']) . "' AND password = '" . mysql_real_escape_string($_POST['password']) . "'");
if (mysql_num_rows($adminCheck) == 1)
{
$result = mysql_fetch_array($adminCheck);
$_SESSION['user']['level'] = "admin";
$_SESSION['user']['userid'] = $result['id'];
$_SESSION['user']['username'] = $result['username'];
}
else
{
$clientCheck = mysql_query("SELECT * FROM clients WHERE username = '" . mysql_real_escape_string($_POST['username']) . "' AND password = '" . mysql_real_escape_string($_POST['password']) . "'");
if (mysql_num_rows($clientCheck) == 1)
{
$result = mysql_fetch_array($clientCheck);
$_SESSION['user']['level'] = "client";
$_SESSION['user']['userid'] = $result['id'];
$_SESSION['user']['username'] = $result['username'];
$_SESSION['user']['client'] = $result['client'];
}
else
{
$response = "invalid login";
}
}
echo $response;
?>

Emails via script get set out 3 times?

I have a email script that runs every 15 minutes and is supposed to send a email once using PHP mailer. For some reason, it's sending out 3 emails a time.
Here's my code:
<?php
// Database connect
include("class.phpmailer.php");
$sql2 = "SELECT * FROM eblast_email WHERE id = '1'";
$result2 = mysql_query($sql2);
while ($myrow2 = mysql_fetch_array($result2)){
$get_event_id = "".$myrow2['event_id']."";
$mail = new PHPMailer();
// Login information here
$mail->Subject = "Subject here";
$html.= "HTML Message here";
$plain = "Plain Message here";
$mail->Body = $html;
$mail->AltBody = $plain;
$sql = "SELECT * FROM email_users WHERE sent = 'no' LIMIT 0, 40";
$result = mysql_query($sql);
while ($myrow = mysql_fetch_array($result)){
$email_to_send_to = "".$myrow['email']."";
$rsvp_check = mysql_query("SELECT * FROM event_members WHERE event_attending='$get_event_id' AND email='$email_to_send_to'");
$rsvp_check_done = mysql_num_rows($rsvp_check);
if ($rsvp_check_done == 0) {
$mail->AddAddress($email_to_send_to);
if(!$mail->Send()) {
echo "<b>Error sending email to " . $myrow['email'] . ". </b>" . $mail->ErrorInfo;
echo "<br>";
} else {
echo "Message to " . $myrow['email'] . " has been sent.<br>";
}
mysql_query("UPDATE email_users SET sent='yes' WHERE email='".$myrow['email']."'") or die (mysql_error());
$mail->ClearAddresses();
} else {
mysql_query("UPDATE email_users SET sent='yes' WHERE email='$email_to_send_to'") or die (mysql_error());
echo "$email_to_send_to has already registered ($rsvp_check_done) -- $get_event_id && $email_to_send_to<br>";
}
sleep(2);
}
}
echo "<br>Done.";
?>
Modify the code to have write to a log file every time it runs. My guess is that it's just getting called 3 times.
Example:
file_put_contents("log.txt", $_SERVER['REQUEST_TIME'] . "\n", FILE_APPEND);

Categories