duanbing8817 2019-06-01 19:39
浏览 101
已采纳

每24小时生成一个新的.txt文件

I'm trying to make a visitor counter with php that will create yy-mm-dd.txt everyday and contain the number of visitors that day and after 12 AM it will create a new yy-mm-dd.txt file. As example today is 2019-06-02 so the text file will be 2019-06-02.txt and in the next day, 2019-06-03.txt file will be automatically created.

Here is what I tried but it is not creating new 2019-06-03.txt file after 12 AM. It keeps the same 2019-06-02.txt file

<?php

    $date = date('Y-m-d');

    $fp = fopen('dates/'.$date.'.txt', "r");

       $count = fread($fp, 1024);

   fclose($fp);

       $count = $count + 1;

       $fp = fopen('dates/'.$date.'.txt', "w");

                 fwrite($fp, $count);

     fclose($fp);

 ?>

How to fix it?

  • 写回答

2条回答 默认 最新

  • douxingmou4533 2019-06-01 21:11
    关注

    Your code should be working fine. We can also add is_dir and file_exists checks, and we can use either fopen, fwrite and fclose or file_get_content/file_put_content, if we like. We can also add a default_timezone such as:

    date_default_timezone_set("America/New_York");
    

    Then, our code would look like something similar to:

    date_default_timezone_set("America/New_York");
    
    $dir = 'dates';
    
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
    }
    
    $count = 1;
    $date = date('Y-m-d');
    $filename = $dir . '/' . $date . '.txt';
    
    if (!file_exists($filename)) {
        $fp = fopen($filename, "w");
        fwrite($fp, $count);
        fclose($fp);
    } else {
        $count = (int) file_get_contents($filename) + 1;
        if ($count) {
            file_put_contents($filename, $count);
        } else {
            print("Something is not right!");
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?