PHP Sending Duplicate Emails - php

After some more troubleshooting I believe I found the problem. We use QR Tags for our product and when a QR code is scanned it takes the user to the URL that runs this script. If I manually type in the URL or if I use our custom built QR scanner app then the user will receive one email. However if I user any other QR scanning app then it will send multiple emails. How can I make it so that this script will run only once each time the URL is loaded even if its from a third party app?
<?php
$queryString = $_SERVER['QUERY_STRING'];
$count=-6;
$id=substr($queryString,$count,6);
//db connection
$db = new mysqli('localhost', '*****', '*****', '*****');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
$query = "SELECT * FROM `****` where id = '$id'";
$result = $db->query($query);
$row = $result->fetch_assoc();
$email = $row['email'];
$ownername = $row['ownername'];
$petname = $row['petname'];
//check to see if tag has been registered
if ($email != "") {
//send email
$datetime = date("D M j G:i:s T Y");
$subject = "Alert";
$mailheader.= "From: " . "Tag Team <support#tag.com>\n";
$mailheader.= "X-Sender: " . "support#tag.com\n";
$mailheader.= "Return-Path: " . "support#tag.com\n";
$mailheader .= "Bcc: support#tag.com";
$body .= "Dear " . $ownername . ", \n\n";
$body .= "" . $petname . "'s Tag has just been scanned.\n\n";
$body .= "Click here to Login :\n";
$body .= "http://www.tag.com\n";
$body .= "********************\n\n";
$body .= "Regards,";
$body .= " \n\n";
$body .= "Tag Team";
$body .= " \n\n";
$body .= "Keeping Pets Safe and Found";
mail($email, $subject, $body, $mailheader ) or die ("Mail could not be sent.");
//end email alert
}
header("Location: http://www.smartphonepettag.com/id/profile.php?id=$id");
mysql_close($db);
?>

In the code snippet I cannot see any reason why your script should be executed more than once but relating to your post yesterday it seems as if something on your mail server is going terribly wrong.
But anyway if it's not an mail server fault the solution would be something like this:
// add this at the very first line
session_start();
// add this in the code
if($_SESSION['send'] != true){
mail($email, $subject, $body, $mailheader ) or die ("Mail could not be sent.");
$_SESSION['send'] = true;
}
This will make sure that the "mail()" function will never be executed twice for the same user.
You can learn more about Session Variables at the PHP manual.

You could create a flag in your database indicating if the email has been sent. Check the flag before sending the email, set it after you send the email.

Related

How to run mail function only once?

I want to send mail (only once) using php when $cstt == 10. I want to prevent sending mail on every time I refresh the page. here is my code
if ($cstt == 10) {
echo "Great";
// SENDING EMAIL
$to = "user#example.com";
$subject = "$tracking_id_user is in transit.";
$message =' Hi user, Simple html message. Best Regards!';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: Company <info#company.com>' . "\r\n";
if(mail($to,$subject,$message,$headers)){
echo "mail send";
}else{
echo "email not sent";
}
}
I did the following tasks to achieve the result.
Created a Table mail_record.
added id and mail_sent columns.
after creating the table, wrote the following code.
Connectin to database
$conn = new mysqli('localhost', 'user_id', 'password', 'databasename');
Accessing the data
$sql = "SELECT * FROM mail_record";
$query = $conn->query($sql);
$row = $query->fetch_assoc();
Accessing database to get mail_sent record.
// GETTING MAIL SENT / NOT RECORD (BLANK = NOT SENT & yes10 = Sent)
$mail_status = $row(['mail_sent']);
// CREATING THE CONDITION
if($cstt == 10 and $mail_status == ''){
// SENDING EMAIL if $cstt = 10 & email is not sent (blank)
$to = "admin#example.com, user#example.com";
$subject = "email subject";
$message ='Hi user, email text';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: Web admin <admin#example.com>' . "\r\n";
if(mail($to,$subject,$message,$headers)){
// ADDING The RECORD THAT EMAIL HAS BEEN SENT FOR ($CSTT == 10)
$sql = "INSERT INTO `mail_record ` (`mail_sent`) VALUES ('yes10')";
if ($conn->query($sql) === TRUE) {
echo "Email sent and record added successfully.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
by adding a if condition / logic we can write a code to execute mail send action only once.
now if you refresh the page the first if condition will give result FALSE because $cstt == 10 TRUE but $mail_status == '' FALSE.
using this method you can be very sure that the mail will be sent only once. no matter how many times page is being refreshed.

Mailer not reaching Microsoft email users

Clients with Microsoft email accounts such as Live or Office 365 are not receiving the Alert email sent out with the code below. Texting feature and Yahoo and Gmail work. A link is run on the computer prompting a location to be shared and an email & text to be sent out.
The email used to send the email out is through Office 365. Can anyone take a look at this. Am I missing something?
I have tried using PHP Mailer, but it does the exact same thing. Any Help!
<html>
<head>
<title>Redirecting</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<?php
setcookie("tracker", 1, time()+1800);
$queryString = $_SERVER['QUERY_STRING'];
//$stripped = substr($queryString,strpos($queryString,"i")+1)
$count=-6;
$id=substr($queryString,$count,6);
//start email alert
//connect to database
//db connection
$db = new mysqli('localhost', 'smart', 'smart', 'smarter');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
// associate carrier with correct ending
$query = "SELECT * FROM `smarter` where id = '$id'";
$result = $db->query($query);
$row = $result->fetch_assoc();
$email = $row['email'];
$emailSMS = $row['emailSMS'];
$ownername = $row['ownername'];
$txt_alert = $row['txt_alert'];
$number = $row['phoneone'] . $row['phonetwo'] . $row['phonethree'] . $row['carrier']; // var works
$emailSMS = 1;
if ($txt_alert == "yes")
{
$email_to = $email . " , " . $number;
}
else if ($txt_alert == "no")
{
$email_to = $email;
}
//check to see if tag has been registered
if ($_COOKIE["tracker"] == 1) {
$number = $row['phoneone'] . $row['phonetwo'] . $row['phonethree'] . $row['carrier']; // var works
//check to see if tag has been registered
$host = "smtp.office365.com";
$port = "587";
$username = "support#xxxx.com";
$password = "xxxxxx";
$datetime = date("D M j G:i:s T Y");
$subject = "Alert";
$mailheader.= "From: " . "Smart Recovery Tag Team <support#xxxx.com>\n";
$mailheader.= "X-Sender: " . "support#xxxx.com\n";
$mailheader.= "Return-Path: " . "support#xxxx.com\n";
$mailheader .= "Bcc: support#xxxx.com";
$body .= "Dear " . $ownername . ", \n\n";
$body .= "Your tag has just been scanned.\n\n";
$body .= "Click here to Login to your profile\n";
$body .= "http://www.tag.com\n";
$body .= "***************\n";
$body .= " Login to your profile to see a map of the last GPS location. \n\n";
$body .= "Scanned on " . $datetime . ". \n\n";
$body .= "Regards,";
$body .= " \n\n";
$body .= "Tag Team";
$body .= " \n\n";
$body .= "Keeping found";
if ($txt_alert == "yes")
{
mail($email, $subject, $body, $mailheader, ) or die ("Mail could not be sent.");
mail($number, $subject, $body, $mailheader, ) or die ("Mail could not be sent.");
}
else if ($txt_alert == "no")
{
mail($email, $subject, $body, $mailheader ) or die ("Mail could not be sent.");
}
//send email
$_COOKIE["tracker"] = 0;
}
header("Location: http://www.smartrecoverytag.com/profile.php?id=$id");
mysql_close($db);
?>
</body>
</html>

Mail function on Live Server is Not sending Mails

I have a website and have enabled to send mail using the By default mail function of php
My code is this
I have tested it from other posts also.. and for me it is correct.. but it is still not sending the message. Please tell me.. where is the problem
<?php
include_once './config.php';
$con=mysqli_connect(mysql_host,mysql_user,mysql_password,mysql_database);
$Roll = $_REQUEST['UserName'];
ini_set('display_errors',1);
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
$confirmCode = md5(uniqid(rand()));
$tbl_name1 = "temp_forgot_acc";
$orderCheck = "DELETE FROM $tbl_name1 WHERE EmailId = '$Roll'";
mysqli_query($con,$orderCheck);
$order = "INSERT INTO $tbl_name1 (EmailId,confirm_code) VALUES ('$Roll','$confirmCode')";
$result = mysqli_query($con,$order);
//if($result)
// {
// ---------------- SEND MAIL FORM ----------------
// send e-mail to ...
$to=$Roll;
// Your subject
$subject="Your Forgot Pass link here";
// From
$header = 'From: Admin <admin#test.com>' . "\r\n";
// Your message
$message="Your Comfirmation link \r\n";
$message.="http://www.test.com/test.html?passkey=$confirmCode&Email=$Roll";
// send email
mail($to,$subject,$message,$header);
// }
echo '{"data":[';
echo "{" . '"Finish":'.'"YES"}';
echo ']}';
}
mysqli_close($con);
exit();
?>
I am able to insert it in the database... but it is not sending the maill.
Try code something like this in your application:
$from = "sender id" // sender must be valid
$subject = "subject";
$message = 'mail from'.$from.'sender';
$to = "receiver id";
// send mail
$headers = 'From: <test#test.com>' . "\n";
$headers .= "MIME-Version: 1.0\n" ;
$headers .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
mail($to,$subject,$message,$headers);
and check what you have in $to value..email id must be correct.

php email approval

I have a small web app where people can send a message via email to a group. Because of spam I will have to make an approval procedure.
The messages are being sent via PHP. How am I doing so I have to accept the message before its send to an email that forward it to the group?
My PHP:
<?php
$errors = '';
$myemail = 'whatever#gmail.com';//<-----Put Your email address here.
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$errors .= "\n FEJL: Alle felter skal udfyldes";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
$email_subject = "Form request";
$times = $_POST["timeslots"];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n FEJL: Ugyldig email adresse";
}
$strTimes = implode($times);
if( empty($errors))
{
$to = $myemail;
$email_subject = "$message \n ";
$email_body = "\n Code: $strTimes \n Navn: $name \n Email: $email_address \n";
$headers = "From: $email_address\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: thx.html');
}
?>
ok so this is a fair size project in itself if you want to use a data queue.
ASSUMING you want to use a database you will need to know the basics of setting one up, how to use and setup tables etc. (as long as you have access to a database anyway).
Here is some connection code:
change peter and abc123 to whatever username and password your database has associated with it.
$con = mysql_connect("localhost","peter","abc123");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db");
I will give you some sample code for inserting rows to the database, selecting rows from the database, acting on that info and deleting rows from the database.
Ok lets start with the mail submission:
This section near the bottom of your code is the data we need to manipulate
$to = $myemail;
$email_subject = "$message \n ";
$email_body = "\n Code: $strTimes \n Navn: $name \n Email: $email_address \n";
$headers = "From: $email_address\n";
$headers .= "Reply-To: $email_address";
So assuming you have a mysql database connection with a table setup in the database this is how you would insert it: (please note this is a basic insert query)
$query = "INSERT INTO queuemails (to, subject, body, headers) VALUES ('" . $to . "', '" . $email_subject . "', '" . $email_body . "', '" . $headers . "')";
mysql_query($query);
Ok so those 2 lines would be added BELOW your set variables.
You then need to provide a method of approval page.
This can be done on the same page but you have to seperate out your mail() function from the rest of the script.
Ok so here is a select script now to be able to VIEW your queue for approval. Please note that I have added an auto increment column to the table that stored your queued mail. This is to be able to select a line in the table more easily as is generates a unique number for that line of data. This column is called mid (standing for "mail identity").
ok so here is the selection script:
$query = "SELECT * FROM queuemail"; //this is only good if you know you wont get millions else you need to limit it
//limited select:
//$query = "SELECT * FROM queuemail LIMIT 0,10"; //selects the first 10
while($m = mysql_fetch_assoc(mysql_query($query))){
echo $m['to'] . " ";
echo $m['subject'] . " ";
echo '<a href=approve.php?mid=' . $m['mid'] . '>Approve</a><br>';
}
Then finally to clean up afterwards, after you have used your mail() function you should delete the line from the database that you have sent.
Here is the code (including the $_GET variable, this is an unsafe method but is sufficient to display the code you would be using).
mail(); //data can be added either from a new select statement or from POSTING it with the form
$query = "DELETE FROM mailqueue WHERE mid='" . $_GET['mid'] . "'";
mysql_query($query);
echo 'Your mail has been sent and deleted from the queue';
Hope this helps.
You can add timestamps to another column in the database automatically so that you can verify spam posting with something like:
if($_SERVER['REQUEST_TIME'] > ($oldtimeofpost + 100)){ //time is in seconds
//do something
}
else{
//warning
}

line break issues with sending phpmail

please i am trying to make the message show on newline as the customer types it, but i am getting /r/n between each line and also trying to make the $body .= $_SESSION['username']; appear on a separate line i have tried to use this example to solve but has not been successful the code is below
<?php require_once("include/session.php");?>
<?php require_once("include/dataconnect.php");?>
<?php require_once("include/functions.php");?>
<?php include("include/mheader.php");?>
<?php
$submit = $_POST['Notify'];
$message = mysql_real_escape_string(htmlentities(strip_tags($_POST['message'])));
//echo "$message";
//die();
if('POST' === $_SERVER['REQUEST_METHOD'])
{
if (isset($message))
{
//Get Email Address
$emails = mysql_query("SELECT email FROM reusers WHERE username = '{$_SESSION['username']}'")or die(mysql_error());
//$emails = mysql_query("SELECT reusers.email FROM reusers INNER JOIN repplac ON reusers.username = repplac.Uname AND reusers.username = '".$_SESSION['username']."'")or die(mysql_error());
$results = (mysql_fetch_assoc($emails)) or die(mysql_error());
$email= $results['email'];
//echo "$email";
//die();
if(mysql_num_rows($emails) == 0){
exit("No email addresses found for user '{$_SESSION['username']}'");
}
$email = mysql_result($emails, 0);
//echo "$email";
//die();
$body = $_SESSION['username']. "<br>"
. nl2br($_POST['message']);
$to = $email;
$subject = "copy of your notification";
$headers = "From: noti#r.co.uk\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'Bcc:noti#r.co.uk' . "\r\n";
mail($to,$subject,$body,$headers);
}
}
?>
<p>
<form action='notification.php' method='Post' class='rl'>
<div>
<label for='message' class='fixedwidth'>Message</label>
<textarea name="message" rows ="7" cols="40" id="message"></textarea>
</div>
<div class='buttonarea'>
<p>
<input type='submit' name='notify' value='Notify'>
</p>
</div>
</form>
</p>
<?php include("include/footer.php");?>
Since it's generally safer to send HTML emails in a more archaic form of HTML I'm going to allow the HTML email content to be HTML 4; so it doesn't need to be XML well formed and nl2br() is acceptable.
You're specifying that the content of your email is HTML so normal line endings, \r, \n and \r\n are pretty much irrelevant.
Try something like:
$body = $_SESSION['username']. "<br>"
. nl2br($_POST['message']);
There's no sanity checks or validation in there but I think that's what you're trying to get it to do.
---- EXAMPLE CODE ----
I've just refactored your code somewhat so I could better see what you're doing (it's just a matter of personal preference) and put comments in to show what I'm getting at with regards to sanity checks and validation.
I've not tested any of this, it's pretty much just an example using your code.
<?php
require_once "include/session.php";
require_once "include/dataconnect.php";
require_once "include/functions.php";
require_once "include/mheader.php";
//sanity checks - ensure the form has been posted and that there IS a message
if($_POST && !empty($_POST['message'])) {
//sanity check - ensure there IS a username
$sUsername = !empty($_SESSION['username']) ? $_SESSION['username'] : "";
if($sUsername) {
//check the username against the database?
$resultEmail = mysql_query("SELECT `email` FROM `reusers` WHERE `username` = '{$sUsername}' LIMIT 0, 1")
or die(mysql_error());
//no result - could throw an Exception here
if(mysql_num_rows($resultEmail) == 0) {
die("No email addresses found for user '{$sUsername}'");
}
//email verified against the database
else {
$sEmail = mysql_result($resultEmail, 0);
//create the email
$headers = "From: noti#r.co.uk\r\n"
. 'MIME-Version: 1.0' . "\r\n"
. 'Content-type: text/html; charset=iso-8859-1' . "\r\n"
. 'Bcc:noti#r.co.uk' . "\r\n";
$to = $sEmail; //assuming the email address retrieved from the database has already been mxrr checked etc...
$subject = "copy of your notification";
$body = $sUsername . "<br>"
//remove slashes as this is going in an email, strip tags and convert newlines to "<br>"
// since you're using iso-8859-1 there shouldn't be any oddities unless someone completes
// the form using an Arabic character set (for instance)
. nl2br(strip_tags(stripslashes($_POST['message'])));
//send the email
if(!mail($to, $subject, $body, $headers)) {
die("sendmail error!");
}
}
}
}
?>
try this;
$body = "Username" . "<br>";
$body .= "test1 message for test 1 message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1
test2 message for test 2
test3 message for test 3";
$body = nl2br($body);
and here what i got

Categories