Reputation: 225
I am sending a report by calling this PHP page daily on my browser. It (too often) sends emails twice (even if I make sure to open a new tab each time).
What's wrong with the code + How can I prevent it?
Here is the code:
<?php
require ("/home/phpmailer/PHPMailer-master/PHPMailerAutoload.php");
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'localhost'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '[email protected]'; // SMTP username
$mail->Password = 'PASSWORD'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->From = '[email protected]';
$mail->FromName = 'FROM NAME';
$mail->ClearAddresses();
$mail->addAddress('[email protected]', 'CLARA'); // Add a recipient
$mail->addCC('email@@ABC.com', 'TOM'); // Add a CC recipient
$mail->addReplyTo('[email protected]', 'Info');
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'EMAIL SUBJECT TITLE';
$mail->Body = file_get_contents('http://ADDRESS-OF-THE-FILE.PHP');
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
$mail->ClearAddresses();
}
?>
Upvotes: 1
Views: 188
Reputation: 20747
I am going to guess that you are using Google Chrome and "Prefetch resources to load pages more quickly" is enabled. Essentially Chrome is fetching the URL before you finish typing so when you finish typing and hit enter then you are requesting it again.
Either turn off prefetching or save the URL to a bookmark and click the bookmark when you need to run the task.
Upvotes: 0
Reputation: 13354
Do as SmartyCoder suggested in the comments.
If you are certain you're the only one hitting it, you might try something quick and dirty with cookies to track, like:
// See if a cookie is set, and if so, compare it to today
// If cookie value == today, die() - stop executing
if ( isset( $_COOKIE['email_reports_lastsent'] ) &&
$_COOKIE['email_reports_lastsent'] == date('Y-m-d') ) die();
// Set the cookie as today's date
setcookie( 'email_reports_lastsent', date('Y-m-d') );
This does NOT solve any issue if other devices/users are hitting your script. It also requires you to be using the same browser to send, and you cannot use Incognito or other private browsing tab.
Upvotes: 1