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?
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!");
}
}
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);
?>
Related
Im using server sent events in php. Here is my code in php.
<?php
header("Cache-Control: no-cache");
header("Content-Type: text/event-stream");
$lastMod = 0;
$filename = "tmp.txt";
$filetext = '';
while (true) {
$time = filemtime("tmp.txt");
if($time != $lastMod){
$lastMod = $time;
$file = fopen($filename, "r");
if ($file == false) {
echo ("Error in opening file");
exit();
}
$counter = $counter +1;
$filesize = filesize($filename);
$filetext = fread($file, $filesize);
fclose($file);
echo 'data: This is a message at time '. $filetext . $time. "\n\n";
}
ob_end_flush();
flush();
if (connection_aborted()) break;
sleep(2);
}
Even if the file was modified the value returned by the filemtime() doesn't change. So data in the file doesn't go to the client. What is the solution for this. Any help is appreciated.
As stated in comments, just add clearstatcache like this:
clearstatcache();
$time = filemtime("tmp.txt");
From PHP documentation:
Note: The results of this function (filemtime) are cached. See clearstatcache() for more details.
I am trying to divide CSV file into 6mb files. Following is the code I have tried.
$file = 'upload/L_10001_20200916183801.csv';
$files = SplitCSVBySize($file, 10001);
function SplitCSVBySize($Existingfiles, $AccountId, $splitSize = "") {
$fh = fopen($Existingfiles, 'r');
$headers = fgetcsv($fh);
$files = array();
$filepath = 'upload/' . 'L_' . $AccountId . '_' . date('YmdHis') . '.csv';
$files[] = $filepath;
$currentFile = $filepath;
$outputFile = fopen($filepath, 'w');
fputcsv($outputFile, $headers);
$rows = 0;
while (!feof($fh)) {
if ($row = $rowPri = fgetcsv($fh))
{
if(filesize($filepath) < 6000000){
fputcsv($outputFile, $row);
} else {
fclose($outputFile);
$rows = 0;
$filepath = 'upload/' . 'L_' . $AccountId . '_' . date('YmdHis') . '.csv';
$files[] = $filepath;
$currentFile = $filepath;
$outputFile = fopen($filepath, 'w');
fputcsv($outputFile, $headers);
fputcsv($outputFile, $row);
}
$rows++;
}
}
fclose($outputFile);
fclose($fh);
return $files;
}
Here challenge is I am not able to check filesize because It always returns same size as it was at very first check. Plese help here, what is wrong or any suggestion.
First of all. function filesize (as well as all other derivatives from stat) is cached. That means, once called on some file, its result will remain the same for the same file.
You need to call clearstatcache() prior to calling this function, to clear the cache.
Second. You don't need to call filesize to obtain the size of the opened file.
You can call fstat on the opened file handle and use 'size' item of the returned array . E.g.:
...
$st = filestat($outputFile);
if($st['size'] < 6000000){
...
And at last you don't need to know size of the file, since you have current file position which is, when writing to the file, equals to its size. You can use ftell to obtain that. I.e.
...
if (ftell($outputFile) < 6000000) {
...
I am trying my php script to read the current count from "counter.txt" file and add 1 and save it back in the counter text file.
$filename = 'counter.txt';
// create the file if it doesn't exist
if (!file_exists($filename)) {
$counter_file = fopen($filename, "w");
fwrite($counter_file, "0");
$counter = 0;
} else {
$counter_file = fopen($filename, "r");
// will read the first line
$counter = fgets($counter_file);
}
// increase $counter
$counter++;
// echo counter
echo $counter;
// save the increased counter
fwrite($counter_file, "0");
// close the file
fclose($counter_file);
The script reads and echos the number fine but it doesn't save the file with the increased number.
Please help
This may not be helpful if this is just a learning exercise to familiarize yourself with the various file functions, but this could be a lot simpler using file_get_contents and file_put_contents.
$file = 'counter.txt';
// default the counter value to 1
$counter = 1;
// add the previous counter value if the file exists
if (file_exists($file)) {
$counter += file_get_contents($file);
}
// write the new counter value to the file
file_put_contents($file, $counter);
Of course, whether or not this will work either this way or the way you're trying to do it totally depends on whether or not the file is writable, so you'll also need to be sure its permissions are set properly.
Works for me:
$counter = 1;
$file_name = 'test.'.$counter.'.ext';
if (file_exists($file_name)) {
$counter++;
fopen('test'.$counter.'.ext' , "w");
}
else {
fopen('test'.$counter.'.ext' , "w");
}
<?php
$filename = 'counter.txt';
// create the file if it doesn't exist
if (!file_exists($filename)) {
$counter_file = fopen($filename, "w");
fwrite($counter_file, "1");
fclose($counter_file);
} else {
$counter_file = fopen($filename, "w+");
$fsize = filesize($filename);
// will read the whole file
$counter = (int) fread($counter_file, $fsize);
$counter++;
fwrite($counter_file, $counter);
fclose($counter_file);
}
Basically, I want to continue adding numbers each time the file already existed. So if $url.php exists, make it $url-1.php. If $url-1.php exists, then make it $url-2.php, and so forth.
This is what I already came up with, but I think it'll only work the first time.
if(file_exists($url.php)) {
$fh = fopen("$url-1.php", "a");
fwrite($fh, $text);
} else {
$fh = fopen("$url.php", "a");
fwrite($fh, $text);
}
fclose($fh);
I use while loops for scenarios like this.
$filename=$url;//Presuming '$url' doesn't have php extension already
$fn=$filename.'.php';
$i=1;
while(file_exists($fn)){
$fn=$filename.'-'.$i.'.php';
$i++;
}
$fh=fopen($fn,'a');
fwrite($fh,$text);
fclose($fh);
All that said, this direction of solutions does not scale well. You do not want to be checking over a 100 file_exists routinely.
Use a while loop with a counter variable $i. Keep incrementing the counter until file_exists() returns false. At that point, the while loop exits and you call fopen() on the filename with the current value for $i;
if(file_exists("$url.php")) {
$fh = fopen("$url-1.php", "a");
fwrite($fh, $text);
} else {
$i = 1;
// Loop while checking file_exists() with the current value of $i
while (file_exists("$url-$i.php")) {
$i++;
}
// Now you have a value for `$i` which doesn't yet exist
$fh = fopen("$url-$i.php", "a");
fwrite($fh, $text);
}
fclose($fh);
i was looking for something similar like this and extended Shad's answer for my needs. i need to make sure that a fileupload doesn't overwrite files which already exist on a server.
i know it's not "save" yet, cause it doesn't handle files without extension. but maybe it is a little help for somebody.
$original_filename = $_FILES["myfile"]["name"];
if(file_exists($output_dir.$original_filename))
{
$filename_only = substr($original_filename, 0, strrpos($original_filename, "."));
$ext = substr($original_filename, strrpos($original_filename, "."));
$fn = $filename_only.$ext;
$i=1;
while(file_exists($output_dir.$fn)){
$fn=$filename_only.'_'.$i.$ext;
$i++;
}
}
else
{
$fn = $original_filename;
}
<?php
$base_name = 'blah-';
$extension = '.php';
while ($counter < 1000 ) {
$filename = $base_name . $counter++ . $extension;
if ( file_exists($filename) ) continue;
}
$fh = fopen($filename, "a");
fwrite($fh, $text);
fclose($fh);
$dirname1 = '../counters';
$dirN = '../uploads';
$extens = ".txt";
$fh = fopen(".$dirname1/$filename.$extens", "w");
if(fopen(".$dirN/$filename.", "r")) {
$count_my_page = (".$dirname1/$filename.$extens");
$hits = file($count_my_page);
$hits[0] ++;
$fp = fopen($count_my_page , "w");
fputs($fp , "$hits[0]");
fclose($fp);
echo $hits[0];
}
each time i open the file, the count should be updated.... but it happens only for the first time.....
Think it might be to do with the increment operator (++), try this:
$hits = file($count_my_page);
$nHits = ((int) $hits[0]) + 1;
$fp = fopen($count_my_page , "w");
fputs($fp , $nHits . "");
fclose($fp);
echo $nHits;
As count you mean the $count_my_page var ? It is declared inside the if scope, so every loop it is created as a new one.
try declare it outside.
Is that all in the same file? If so, your first fopen with "w" mode will truncate the file before you read it.