Awani
Awani

Reputation: 404

Limiting number of emails being sent using PHP

I have the following code using which I wish to send emails to users every Sunday:

     if ($day == 'Sun') {
        $servername = "localhost";
        $username = "root";
        $password = "";


        $conn = new mysqli($servername, $username, $password);

        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }

        $result = mysqli_query($conn, "SELECT email FROM sampledb.registration WHERE choice='weekly' AND mailaboute='Epidemic'");


        while ($row = mysqli_fetch_row($result)) {

            $to = $row[0];
            $subject = "Weekly updates";
            $message = "Dear subscriber" . "<br />" . "<br />"; //cwrite nice message
            /*while ($j < 5) {
                $message.=$array[$j];
                $message.="<br>";
            }*/
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type: text/html;charset=iso-8859-1" . "\r\n";
            $headers .= "From: [email protected]" . "\r\n";
            $retval = mail($to, $subject, $message, $headers);
            if ($retval == true) {
                echo "<div class = 'emailSent'>";
                echo "<center><h1>Email sent</h1></center>";
                echo "<center><h2>Please check your email</h2></center>";
                echo "</div>";
            } else {
                echo "Email could not be sent...";
            }
        }

        $conn->close();
    }

However, the problem which I'm facing is that this code is being executed every time the page loads, that means if I open this page 10 times on a Sunday, I will receive 10 emails. How can I change the functionality so that after 1 email is sent, the code should not get executed again.

Upvotes: 2

Views: 38

Answers (1)

Drakes
Drakes

Reputation: 23670

If you go with my cron job suggestion, here is a script that will call your PHP page once every Sunday at 9 AM. It basically fetches your PHP like you would type it in a browser, sends the output to stdout with the -o flag, but really sends the output and any errors to a sinkhole so you don't see them with >/dev/null and 2>&1, respectively.

* 9 * * 0 wget -O - http://yoursite.com/emailer.php?param=val >/dev/null 2>&1

Here are great examples of cron scripts with many different options, for example, supplying a password: http://www.labnol.org/software/wget-command-examples/28750/

Upvotes: 1

Related Questions