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条)

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了