increasing the count on read - php

$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.

Related

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?
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);
?>

incrementing counter in multiple text file

I'm trying to increment a counter in a multiple text file when a user visit my page, but the code I'm working is not working below is the code
$files = glob("counters/visit/*.txt");
foreach($files as $file) {
$content = file_get_contents($file);
if(!isset($_SESSION['hasVisited'])){
$_SESSION['hasVisited']="yes";
$content++;
$f = fopen($files, "w");
fwrite($f, $content);
fclose($f);
}
}
First make sure that $contentis an integer by doing the following :
$content = intval(file_get_contents($file));
Then you're using :
$f = fopen($files, "w");
Instead of :
$f = fopen($file, "w");
fopen can't accept an array as parameter
Also as mentioned by #alanlittle, if you want all your files to be incremented, you should think about the moment where you set $_SESSION['hasVisited']="yes"; and put it at the end of the loop.

Open txt file grab the number count +1 and save it again

I have a text file number.txt and inside it there is only the number 1.
I'm using the code below to open the file, get the number, add 1, update the content (must be 2) and save it again. My code is not working. Any suggestions?
$fp = fopen('number.txt', 'c+');
flock($fp, LOCK_EX);
$count = (int)fread($fp, filesize('number.txt'));
ftruncate($fp, 0);
fseek($fp, 0);
fwrite($fp, $count + 1);
flock($fp, LOCK_UN);
fclose($fp);
Works for me
<?php
$handle = fopen("test.txt", "r+");
if ($handle) {
$buffer = fgets($handle, 10);
$nCount = (int)$buffer;
rewind($handle );
fputs($handle, $nCount+1);
fclose($handle);
}
?>
You should be able to do this with just
$path = 'number.txt';
file_put_contents($path, 1+(int)file_get_contents($path));

How to insert string before last line?

I saw using fseek to insert string before last line this question, but this isn't solving my problem. I not use "?>" tag. Php version PHP 5.4
example line1
example line2
//i need insert here
lastline $eg};
My code is working but this is adding empty lines after all lines :
$filename = 'example.php';
$arr = file($filename);
if ($arr === false) {
die('Error' . $filename);
}
array_pop($arr);
file_put_contents($filename, implode(PHP_EOL, $arr));
/// I'm deleting last line here
$person = "my text here\n";
file_put_contents($filename, $person, FILE_APPEND);
$person = "andherelastline";
file_put_contents($filename, $person, FILE_APPEND);
//and then add again here
$file = "tmp/saf.txt";
$fc = fopen($file, "r");
while (!feof($fc)) {
$buffer = fgets($fc, 4096);
$lines[] = $buffer;
}
fclose($fc);
//open same file and use "w" to clear file
$f = fopen($file, "w") or die("couldn't open $file");
$lineCount = count($lines);
//loop through array writing the lines until the secondlast
for ($i = 0; $i < $lineCount- 1; $i++) {
fwrite($f, $lines[$i]);
}
fwrite($f, 'Your insert string here'.PHP_EOL);
//write the last line
fwrite($f, $lines[$lineCount-1]);
fclose($f);

How do I prepend file to beginning?

In PHP if you write to a file it will write end of that existing file.
How do we prepend a file to write in the beginning of that file?
I have tried rewind($handle) function but seems overwriting if current content is larger than existing.
Any Ideas?
$prepend = 'prepend me please';
$file = '/path/to/file';
$fileContents = file_get_contents($file);
file_put_contents($file, $prepend . $fileContents);
The file_get_contents solution is inefficient for large files. This solution may take longer, depending on the amount of data that needs to be prepended (more is actually better), but it won't eat up memory.
<?php
$cache_new = "Prepend this"; // this gets prepended
$file = "file.dat"; // the file to which $cache_new gets prepended
$handle = fopen($file, "r+");
$len = strlen($cache_new);
$final_len = filesize($file) + $len;
$cache_old = fread($handle, $len);
rewind($handle);
$i = 1;
while (ftell($handle) < $final_len) {
fwrite($handle, $cache_new);
$cache_new = $cache_old;
$cache_old = fread($handle, $len);
fseek($handle, $i * $len);
$i++;
}
?>
$filename = "log.txt";
$file_to_read = #fopen($filename, "r");
$old_text = #fread($file_to_read, 1024); // max 1024
#fclose(file_to_read);
$file_to_write = fopen($filename, "w");
fwrite($file_to_write, "new text".$old_text);
Another (rough) suggestion:
$tempFile = tempnam('/tmp/dir');
$fhandle = fopen($tempFile, 'w');
fwrite($fhandle, 'string to prepend');
$oldFhandle = fopen('/path/to/file', 'r');
while (($buffer = fread($oldFhandle, 10000)) !== false) {
fwrite($fhandle, $buffer);
}
fclose($fhandle);
fclose($oldFhandle);
rename($tempFile, '/path/to/file');
This has the drawback of using a temporary file, but is otherwise pretty efficient.
When using fopen() you can set the mode to set the pointer (ie. the begginng or end.
$afile = fopen("file.txt", "r+");
'r' Open for reading only; place
the file pointer at the beginning of
the file.
'r+' Open for reading and
writing; place the file pointer at the
beginning of the file.
$file = fopen('filepath.txt', 'r+') or die('Error');
$txt = "/n".$string;
fwrite($file, $txt);
fclose($file);
This will add a blank line in the text file, so next time you write to it you replace the blank line. with a blank line and your string.
This is the only and best trick.

Categories