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.
Related
This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 12 months ago.
I have been trying to add form submit to my web form, so that it submits data to my email using POST.
So far this is what I have and it works perfectly:
<?php
if(isset($_POST['submit'])){
$user = $_POST['user'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$to = "your-webmail here";
$subject = "Applied Data";
$txt = "Name-'.$user.',<br>Phone -'.$phone.',<br>Email-'.$email.'";
$headers = "From: your#gmail.com" . "\r\n" .
$headers .= 'Cc: your#gmail.com' . "\r\n";
$ab=(mail($to,$subject,$txt,$headers));
if($ab)
{
echo"<script>alert('SignUp successfully.')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
else
{
echo"Failed";
}
}
?>
Is there a way to add a redirect to this code, so it redirects after form is submitted?
You have two options (probably more...)
Refactor your code to use AJAX to process the results of the form;
Don't display the headers until you know whether the form has been submitted / processed correctly. A redirect won't work if headers have already been sent.
As you've provided a non-AJAX problem:
<?php
if(isset($_POST['submit'])){
$user = $_POST['user'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$pageHeaders = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"; // etc.
$to = "your-webmail here";
$subject = "Applied Data";
$txt = "Name-'.$user.',<br>Phone -'.$phone.',<br>Email-'.$email.'";
$headers = "From: your#gmail.com" . "\r\n" .
$headers .= 'Cc: your#gmail.com' . "\r\n";
$ab=(mail($to,$subject,$txt,$headers));
if($ab)
{
header("Location: index.php");
die();
}
else
echo $pageHeaders; // You will need to create page headers
echo"Failed";
}
}
?>
This solution doesn't allow for an alert or message to indicate successful save. This could be achieved by redirecting to an interstitial page which can redirect after a timer. See here for an example:
use $_SESSION or $_COOKIE or a flag in your DB/in a temporary file to read & write.
for example:
if (isset($_SESSION['mail_sent']) && $_SESSION['mail_sent'] === true) {
redirect_to($target_url);
exit;
}
if(isset($_POST['submit'])) {
...
if (sending was successful) {
$_SESSION['mail_sent'] === true
}
else {
$_SESSION['mail_sent'] === false
}
}
I want to send diifferent email to both admin and user.I dont know how to do that.
The code which i am sharing with you is sending same email to both admin and user.Please help me ..
Here is my code ;
$car = $_POST['category'];
$pick = $_POST['text1'];
$drop = $_POST['text2'];
$source = $_POST['text3'];
$email= $_POST['text4'];
$to="$email";
$subject="Web Enquiry";
$message="Hi,". "\r\n" . "\r\n" .
"You've received an email with following details, from the inquiry made at the website- mail#silvertaxi.com" ."\r\n"."\r\n".
"Car Category:"." "."$car"."\r\n".
"Source Location:"." "."$pick"."\r\n".
"Destination Location:"." "."$drop"."\r\n".
"Day and Time.:"." "."$source". "\r\n".
"Email:"." "."$email". "\r\n" ."\r\n".
"Thanks & Regards,". "\r\n" .
"Web Admin"."\r\n" ;
$headers ="From:$email\n";
$headers .= 'Cc: admin#email.com' . "\r\n";
$headers.="MIME-Version: 1.0\n";
$headers.="Content-type: text/html; charset=iso 8859-1";
if(mail($to, $subject, $message,$headers))
{
echo "Your Message has been sent." ;
} else {
echo "";
}
You should call mail() function twice; one for user and another for admin. Remove the line
$headers .= 'Cc: admin#email.com' . "\r\n";
from your code.
Then, define different messages for user and admin as you want.
$to="$email";
$subject="Web Enquiry";
$message="....." //your message to user goes here
$to_admin = "admin#email.com";
$subject_admin = "...."; //subject for mail to admin
$message_admin = "....." //your message to admin goes here
Use the mail() function twice to send different emails.
if((mail($to, $subject, $message,$headers) && mail($to_admin, $subject_admin, $message_admin, $headers))
{
echo "Your Message has been sent." ;
} else {
echo "";
}
firstly you need to check he is user or admin. If he is user you can add a condition statement for its another for admin. Like this:
if($user_role == "user"){
//mail for user
.....
}
if($user_role == "admin"){
//mail for admin
.....
}
If you have any question feel free to ask.
I want to send mass emails using PHP mail function. Email addresses are stored in MySQL database. There are nearly 30k email addresses. I am sending one email at a time.
60 emails are sent properly & the next all emails are skipped. I am using godaddy host to send emails. Following is code I am using
<?php
$con1=mysqli_connect("subscibe","subscibe","pw","subscibe");
$subject = $_POST['subject'];
$message = $_POST['message'];
$getusers = mysql_query("SELECT * FROM subscibe.emaillist");
$email_from = "email#gmail.com";
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
while($result = mysql_fetch_array($getusers)) {
$emailaddress = $result['Emailaddresses'];
mail($emailaddress,$subject,$message,$headers);
//Add email address to temp table
$sqlq="INSERT INTO subscibe.temp VALUES ('$emailaddress')";
if (!mysqli_query($con1,$sqlq)) {
die('Error: ' . mysqli_error($con1));
}
}
echo "Emails are sent"
?>
you may want to use a foreach loop which would send the email to each record in your DB.
Something like:
$getusers = mysql_query("SELECT * FROM subscibe.emaillist");
foreach ($getusers as $maillist) {
$mail->to($mailist['email_address']);
$mail->send()
<?php
$con = mysql_connect("localhost","dbuser","dbpass"); // replace dbuser, dbpass with your db user and password
mysql_select_db("dbname", $con); // replace dbname with your database name
/*
To use this script database table must have three fields named sno, email and sub_status
*/
$query = "select sno, email from dbtable where sub_status = 'SUBSCRIBED'";
$result = mysql_query($query, $con);
$emails = array();
$sno = array();
while($row=mysql_fetch_assoc($result))
{
$sno[] = $row['sno']; // this will be used to unsubscribe the user
$emails[]=$row['email']; // email id of user
}
/* you can also get email id data from CSV using below code */
//$file = file_get_contents("travel_database.csv");
//$emails = explode(",",$file);
/* count.txt is used to store current email sent number/count */
$count = file_get_contents("count.txt");
for($i=$count;$i<count($emails);$i++)
{
$to = $emails[$i];
// subject
$subject = 'Set Your Title Here';
// message
$message = file_get_contents("sample.html"); // this will get the HTML sample template sample.html
$message .= '<p>Please click here to unsubscribe.</p>
</body>
</html>';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
//$headers .= "To: $to" . "\r\n";
$headers .= 'From: Name <info#yourdomain.com>' . "\r\n";
//$headers .= 'Cc: sendcc#yourdomain.com' . "\r\n";
//$headers .= 'Bcc: sendbcc#yourdomain.com' . "\r\n";
// Mail it
if(mail($to, $subject, $message, $headers)) {
$file = fopen("mailsentlist.txt","a+"); // add email id to mailsentlist.txt to track the email sent
fwrite($file, $to.",\r\n");
fclose($file);
}
else
{
$file = fopen("notmailsentlist.txt","a+"); // add email to notmailsentlist.txt here which have sending email error
fwrite($file, $to.",\r\n");
fclose($file);
}
if(($i-$count)>=200) // this will send 200 mails from database per execution
{
$filec = fopen("count.txt",'w'); // store current count to count.txt
fwrite($filec, $i);
fclose($filec);
break;
}
}//for end
$filec = fopen("count.txt",'w'); // store fine count to count.txt this will be used as a start point of next execution
fwrite($filec, $i);
fclose($filec);
?>
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.
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.