phpfuelphp

Send an email after 5 minutes by comparing 2 datetimes using PHP and FuelPHP framework


I am using MVC framework called FuelPhp I am aware this is an old framework but this is what the application runs on.

Trying to send an email comparing two datetimes, so if the website is down which is recorded in $down_timeand five minutes have passed which is recorded in the $last_checked_time then an email should send. The problem I am having is the code seems to stop at this line $difference = $last_checked_time->diff($down_time); and is never hitting the if statement. Basically all I want to do is to check if the $last_checked_time is greater than the $down_time by 5 minutes. There are no errors been logged so I'm unsure what the problem is, I would really appreciate the help thank you.

                    $down_time = DateTime::createFromFormat('Y-m-d H:i:s', $website->down_at);
                    $last_checked_time = DateTime::createFromFormat('Y-m-d H:i:s', $website->last_checked);

                    $difference = $last_checked_time->diff($down_time);

                    if ($difference->format("a") > 0 || $difference->format("h") > 0 || $difference->format("m") >= 5) {

                        Cli::write("Emailing: " . $website->url . " is offline");

                        $notify_emails = array();

                        foreach ($services as $service)
                        {
                            $service_id = $service->service_id;
                            if (in_array($service_id, $dept_emails))
                            {
                                $notify_emails[] = $dept_emails[$service_id];
                            }
                        }

                        $message = "Hi," . $website->url . " has been down since " . $website->down_at . ".";
                        $email = Model_Mail::send_email($dept_emails, "" . $website->url . " is down", $message);

                        $result = DB::update('clients_websites')
                            ->set(array(
                                'down_email_sent' => date('Y-m-d H:i:s')
                            ))
                            ->where('id', '=', $website->id)
                            ->execute();
                    }

Solution

  • When calling format you need to use a % symbol in front of the format string:

    if ($difference->format("%a") > 0 || $difference->format("%h") > 0 || $difference->format("%m") >= 5) {
    

    Also, %m is months. If you want minutes you should use %i.

    edit

    Also again, the DateInterval class can be annoying because you have to check many properties, it might be easier to just deal with seconds:

    $diff_in_seconds = $last_checked_time->getTimestamp() - $down_time->getTimestamp();
    if($diff_in_seconds >= 300){
        //Do something
    }