Send email at the end of each month

Asked

Viewed 63 times

-2

I have a user subscription system, I need to send a notification every end of month warning that the subscription is coming due, the problem is that I don’t know how to make this script run automatically without me having to access a particular page for it to run, I will try to give an example in a simplistic way:

Let’s assume I want to send this email on October 2nd, so I would do like this:

$data_programada = '02/10/2018';
if(date('d/m/Y') == $data_programada) {

    mail('[email protected]','vencimento','mensagem de vencimento');

}

the problem is that this email will only be sent if I access the page that contains this script, I need you to do it automatically

1 answer

-1

What you want is a Cronjob: What are CRON JOBS and how to use them with PHP

This example uses the Unix/linux cron mechanism, which is the most common to use, but there are mechanisms that integrate directly into the language, as is the case of Quartz for Java, but I don’t know any of this for PHP.

My tip: Use linux cron :)

Complementing the answer:

You need to add a cron entry to your system user (linux):

Step 1: Create the file that will be executed: helloworld.php file

<?php

echo 'Hello world';

?>

Step 2: Start the change in the system cron file using the 'crontab -e' command. This command will open the cron file using the default editor, probably vim

Step 3: Add the desired cron entry with the file that was created. In this example I will put to run every first day of the month at 9 am:

0 9 1 * * php -f /home/murilo/meu_php/helloworld.php > /dev/null 2>&1

Description:

0 9 1 * * -> Expressão cron para executar em todo primeiro dia do mes as 9 da manhã (para mais exemplos acesse https://crontab-generator.org/)

php -f /home/murilo/meu_php/helloworld.php -> Comando a ser executado

> /dev/null 2>&1 -> Direcionando sysouts para /dev/null

Step 4: Save the file and ready, it is configured !

To perform exactly at the end of the month is a little more complicated, as the months have different end days (can end on 28, 29, 30 or 31) the expression cron gets a little more complicated. The easiest way I found was to create more than one cron entry to cover the different cases.

Behold:

https://stackoverflow.com/questions/6139189/cron-job-to-run-on-the-last-day-of-the-month

https://blog.nexcess.net/2013/05/09/cron-job-for-the-last-day-of-the-month/

  • need to have a vps to do this? a shared hosting has as?

  • As far as I know it is possible to do this in a shared hosting. I advise contacting your hosting to know how to do, as they can use different settings, such as php installation location and etc.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.