Send email notifications with php

Written by Mark Sanborn: Jul 17, 2007

In order to send an email notification on your site via php you will probably need some sort of scheduled task program. This will execute the php script routinely. Since I tend to use open source software I used cron. Cron is found in Unix and Unix-like operating systems and is used to schedule commands to be executed periodically. It reads a series of commands from standard input and collects them into a file known as a “crontab” which is later read and whose instructions are carried out.

An example of a cron entry in crontab that would execute every five minutes:

5 * * * * /usr/local/bin/php /home/myuser/mydomain.com/notifications.php This line also includes the program in which to open the php file.

For more information about using cron check out, Learning cron by Example.

Now that we have a program set up to execute our script we need to prepare our php file.

This line will tell cron which binary program to execute the script. In this case it is php.

#!/usr/local/bin/php -q

Note: This is not necessary if you include this in cron.

Here is the php code I came up with to get the job done.

function isExpired($expireDate,$emailAddress,$subject,$body) {
    $expireDate = strtotime($expireDate); // Must be in m/d/y format!
    $now = time(); // Get current date
    if ($expireDate < $now) {
        mail($emailAddress, $subject, $body);
    }
}

Need to print shipping labels on your site?

Checkout my product RocketShipIt for simple easy-to-use developer tools for UPS™ FedEx™ USPS™ and more.

Share: