incrementing counter in multiple text file - php

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.

Related

PHP to Increase counter by 1 and save in a txt file

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

Read all txt files in a specific folder and write all contents in one txt file

I try to read all *.txt files from a folder and write all content from each file into another txt file. But somehow it only writes one line into the txt file.
I tried with fwrite() and file_put_contents(), neither worked.
Here is my code:
<?php
$dh = opendir('/Applications/XAMPP/xamppfiles/htdocs/test/');
while($file = readdir($dh)) {
$contents = file_get_contents('/Applications/XAMPP/xamppfiles/htdocs/test/' . $file);
$dc = array($contents);
}
file_put_contents('content.txt', $dc);
?>
This should work for you:
(Here I get all *.txt files in a directory with glob(). After this I loop through every file with a foreach loop and get the content of each single file with file_get_contents() and I put the content into the target file with file_put_contents())
<?php
$files = glob("path/*.txt");
$output = "result.txt";
foreach($files as $file) {
$content = file_get_contents($file);
file_put_contents($output, $content, FILE_APPEND);
}
?>
try this
$contents = array();
$line = file(/*next file in dir*/);
foreach($lines as line){
array_push($line, $contents);
}
//File path of final result
$filepath = "mergedfiles.txt";
$out = fopen($filepath, "w");
//Then cycle through the files reading and writing.
foreach($filepathsArray as $file){
$in = fopen($file, "r");
while ($line = fgets($in)){
print $file;
fwrite($out, $line);
}
fclose($in);
}
//Then clean up
fclose($out);
return $filepath;

Fopen problems in php

In PHP im creating a tool to open txt file with an integer in it, increment the number, save the number to a variable and then save and close the file. this is the code i have for it and it doesnt seem to work when i have it on my test server. Can anyone clue me in as to why this isnt working properly?
//opens pclnumber.txt to $handle, saves number to $number, Increments number in text file, saves and closes file
$handle = fopen("pclnumber.txt", "w+");
$number = fread($handle);
fwrite($handle, $number+1);
fclose($handle);
over all you must set reading permission on your file, and than you can use the follow code:
$filename = "pclnumber.txt";
//read file content
$handle = fopen($filename, "r");
$number = fread($handle, sizeof($filename));
fclose($handle);
//update file content
$handleWrite = fopen($filename, "w+");
fwrite($handleWrite, $number+1);
fclose($handleWrite);
Bye,
Marco

Splitting a text file in half using PHP?

I want to take one text file, split it in half, and put one half in one file, then the remaining half in the next. How would one accomplish this?
an example would be: split.php?n=file.txt
$file = $_GET['n'];
$i = 1;
$fp = fopen("./server/php/files/".$file,'a+');
$fs = filesize("./server/php/files/".$file);
$lengthhalf = $fs / 2;
while(! feof($fp)) {
$contents = fread($fp,$lengthhalf);
file_put_contents('./server/php/files/[2]'.$file,$contents);
$i++;
}
This does the work, without reading the whole file (or half of it) at once in memory:
function split_in_halves($file, $half1, $half2) {
$size = filesize($file);
$fd = fopen($file, 'rb');
stream_copy_to_stream($fd, fopen($half1, 'wb'), $size/2);
stream_copy_to_stream($fd, fopen($half2, 'wb'));
}
split_in_halves('foo', '[1]foo', '[2]foo');

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