我是php的新手,所以请注意这是一个简单的问题。我有一个php脚本,我希望它每天只被执行10次,不超过这一点。我不想使用cron来解决这个问题。有没有办法只在php中做到这一点?
现在,我已经设置了一个计数器,它会在任何人运行脚本时递增1,并仅循环10次。如果超过该值,将显示一条错误消息。
function limit_run_times(){
$counter = 1;
$file = 'counter.txt';
if(file_exists($file)){
$counter += file_get_contents($file);
}
file_put_contents($file,$counter);
if($counter > 11 ){
die("limit is exceeded!");
}
}我想要一些有效的方法来做到这一点,所以每天脚本只执行10次,这适用于每天,即这个计数器每天被刷新到0,或者有任何其他有效的方法。
发布于 2019-05-15 13:53:22
我更倾向于建议你使用数据库--它更干净,更易于维护。
但是,它也可以通过文件处理来实现。该文件的格式为2019-05-15 1 (用制表符、\t分隔)。获取文件的内容并按explode()拆分值。然后进行比较和检查,并相应地返回值。
function limit_run_times() {
// Variable declarations
$fileName = 'my_log.txt';
$dailyLimit = 10;
$content = file_get_contents($fileName);
$parts = explode("\t", $content);
$date = $parts[0];
$counter = $parts[1] + 1;
// Check the counter - if its higher than 10 on this date, return false
if ($counter > $dailyLimit && date("Y-m-d") === $date) {
die("Daily executing limit ($dailyLimit) exceeded! Please try again tomorrow.");
}
// We only get here if the count is $dailyLimit or less
// Check if the date is today, if so increment the counter by 1
// Else set the new date and reset the counter to 1 (as it is executed now)
if (date("Y-m-d") !== $date) {
$counter = 1;
$date = date("Y-m-d");
}
file_put_contents($fileName, $date."\t".$counter);
return true;
}https://stackoverflow.com/questions/56142124
复制相似问题