man
man

Reputation: 173

Generate a new .txt file every 24 hour

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?

Upvotes: 0

Views: 453

Answers (2)

stefo91
stefo91

Reputation: 618

Better use file_get_contents then file_put_contents:

<?php
$count = 1;
$content = file_get_contents(date('Y-m-d').'txt');
if($content !== FALSE){
   $count+=(int)$content;
}
file_put_contents(date('Y-m-d').'txt', $count);
?>

Upvotes: 1

Emma
Emma

Reputation: 27723

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!");
    }

}

Upvotes: 2

Related Questions