How to limit firing rate of mail() in a php script

I am using a function that detects whenever there is a db connection problem and sends me an email notification using mail(). The function can be found here: http://www.remicorson.com/create-a-wordpress-database-error-page/

The problem is, the mails are fired every time a user tries to access the page, leading to 1000s of emails if there is a database connection error that persists for quite some time.

Read More

I was wondering what is a good wait to set up something like a timer that will prevent this behaviour (it would be great if we could set it to max 1 execution every 5 mins for example)

Thank you

Related posts

1 comment

  1. If I were you, I would generate a log file. I would ideally generate a log in the database, but in your case you are reporting database issues, so the log would most likely not get generated.

    Create a text file log that you can easily parse, and make sure you use a time stamp for each entry. Then before you send an email, check the time stamp of the last entry in the log. If it’s greater than x number of seconds, minutes, hours, days, whatever… then send the email.

    This way you have a good log of what’s happening, and you’ll receive email notification only when you want one for each database failure.

    The order would go…

    1. Error happens
    2. Parse log file and get time stamp of last entry
    3. Log new event to log file
    4. Send email if criteria dictates

    Here’s an article to get you started on generating a text based log:

    https://web.stanford.edu/dept/its/communications/webservices/wiki/index.php/How_to_create_logs_with_PHP

    Customize it to your level of parsing experience, so you can always find the time stamp you need.

    UPDATE

    As I was reading more from the link I sent you, they provide a link to another article that does exactly what I was taking about:

    https://web.stanford.edu/dept/its/communications/webservices/wiki/index.php/How_to_create_a_flood-proof_e-mail_log_in_PHP

    In this case they use a text file to simply hold the time stamp of the last event and store their log in the database. Customize to your liking! Best of luck!

Comments are closed.