A counter associated with a server in PHP that will reset to zero every midnight, or at least

I would like to know how best to implement in PHP a counter that was incremented by some events on the server during the day, would reset to zero with the advent of a new day, that is, at midnight. Probably comparing the date associated with the last counter value with the current date would make it reset?

EDIT: what if the counter gets reset the moment it is incremented, if the code somehow finds out that the last time the counter was incremented was yesterday or the day before? It would be nice.

+4
source share
2 answers

Do you save your counter in the database? If so, you can simply save the date of the last change along with it. Let me assume that you have table counters (name, value, date), then the following pseudo code might give you an idea:

$counter_id='herpderp'; $today = date('dMY'); $date, $value = query("SELECT date, value FROM counters where name='$counter_id'"); if ($date!=$today) { $value = 0; query("UPDATE counters SET date='$today', value=1 WHERE name='$counter_id' AND date='$date'"); } else { query("UPDATE counters value=value+1 WHERE name='$counter_id' AND date='$date'"); } echo $value; 
+2
source

Depending on your server, you can either implement the scheduled task (Windows) or CRON Job (Linux). This will be what allows your script to execute at a specific time of day (or night).

As for the counter, you can implement this in several ways. For data integrity and security, I would store the value in the database. To increase, select a value and increase it (there are also some ways, depending on your DBMS, to do this with a single SQL query). Otherwise, you can always edit the configuration file with I / O commands in PHP.

Setting up a CRON job / scheduled task

If you give me more information about your server configuration, I can give you specific tutorials on where you can learn how to set up your task.

Once you find out, you'll want to call a specific script. Your script in PHP can be configured as follows:

Compare the current D / M / Y with the previous days, most likely stored in your database or configuration file. If this happens, update your database / file by performing any analytical steps that you consider appropriate.

+1
source

Source: https://habr.com/ru/post/1399698/


All Articles