How to stop .txt from getting too big PHP - php

Hello,
I am making my first PHP using website and I have some things that I am writing to a log.txt. Everytime someone visits my website something gets written like this:
$dateTime = date('Y/m/d G:i:s');
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Date / Time: '."".$dateTime ."\n\n");
fclose($fh);
Now I would like to know, how to set a max file size for my log.txt to stop it from getting too big. For example; it'll auto delete the oldest content "block" of let's say 6 lines long and replace it with the new one after the file has exceeded (for example) 500 lines.
I couldn't find this problem online so I am very curious to how I would do this.
If you have any questions please let me know and I hope you can help me with this problem!

Please try this code. I have tested it it works fine. I use \r\n for line break so that your text file is more readable.
$dateTime = date('Y/m/d G:i:s');
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Date / Time: ' . "" . $dateTime . "\r\n");
fclose($fh);
now you check if the number of lines in the file exceed your limit, then remove the old lines from the top the the file and enter new line on the top, else just enter new line.
$block = 5; //block consist of 5 lines
$remove_blocks = 10; //remove the number of blocks
$remove = $block * $remove_blocks; //totle line to remove
$line_limit = 20;
$content = file_get_contents("log.txt");
$array = explode("\r\n", $content);
$count = count($array);
if ($count >= $line_limit) {
//Remove first few lines
$array = array_slice($array, $remove);
$new_data = implode("\r\n", $array);
$fh = fopen('log.txt', 'w');
fwrite($fh, $new_data . "\r\n");
fclose($fh);
} else {
$dateTime = date('Y/m/d G:i:s');
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Date / Time: ' . "" . $dateTime . "\r\n");
fclose($fh);
}
Edit: put this code in a new test.php adn experiment with it
<?php
$block = 2; //block consist of 5 lines
$remove_blocks = 1; //remove the number of blocks
$remove = $block * $remove_blocks; //totle line to remove
$line_limit = 5;
$content = file_get_contents("log.txt");
$array = explode("\r\n", $content);
$array = array_slice($array, -1);
$count = count($array);
if ($count >= $line_limit) {
//Remove first few lines
$array = array_slice($array, $remove);
$new_data = implode("\r\n", $array);
$fh = fopen('log.txt', 'w');
fwrite($fh, $new_data . "\r\n");
fclose($fh);
$dateTime = date('Y/m/d G:i:s');
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Date / Time: ' . "" . $dateTime . "\r\n");
fclose($fh);
} else {
$dateTime = date('Y/m/d G:i:s');
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Date / Time: ' . "" . $dateTime . "\r\n");
fclose($fh);
}
?>

I suggest using "rotation log files" for this instead. Research on google about this. You will get some easy solutions for it.
For example How to configure logrotate with php logs

Here is an Example how to get Lines Count from File https://www.w3resource.com/php-exercises/php-basic-exercise-16.php
or you can try to get file Size:
if(filesize("log.txt") >= 5000){ echo "file to is large"; }
or
$content = file_get_contents("log.txt");
$array = explode("\n", $content);
$count = count($array);
if($count >= 500){
echo "file too large";
}

You can name the file with the date as a filename
So basically for each day you will have another file
$dateTime = date('Y/m/d G:i:s');
//The file will have the name log_2019-10-09.txt
$fh = fopen('log_'.date('Y-m-d').'.txt', 'a');
fwrite($fh, 'Date/Time: '."".$dateTime ."\n\n");
fclose($fh);

Related

PHP file-writing problems

I have a file called "number.txt"(there is a number inside, e.g.: 0 )
And I want to read the number inside the number.txt and use fwrite to write the number plus 1
(number+1), so that each time anyone visit this webpage, the number will add 1.
but when i test it, it only works at first time(now number.txt is 1).
Then i try another time, the fread function read 0 but not 1.
<?php
$fgc = file_get_contents('number.txt');
settype($cont, "integer");
$cont = $cont + 1;
settype($cont, "string");
file_put_contents('number.txt', $cont);
$str = settype($cont, "string");
$fp = fopen( $str ,'w+');
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
$da = $_GET['data'];
fwrite($fp, $da);
fclose($fp);
?>
And why not to do simple like this:
file_put_contents('numbers.txt', is_writeable('numbers.txt')?((int)file_get_contents('numbers.txt'))+1:exit('Failed to open file'));
Borrowing on Eugene's great one-liner, came up with the following solution.
(Credit goes to go Eugene)
The following code will create the file if it does not exist, and increment by +1 each time it is reloaded.
(Tested)
<?php
$filename = "number.txt";
$filename = fopen($filename, 'a') or die("can't open file");
file_put_contents('number.txt', ((int)file_get_contents('number.txt'))+1);
// To show (echo) the contents of the file, you can use one of the following
// include("number.txt");
// echo file_get_contents('number.txt');
?>
It is because you are setting the write data to the old GET var and not the new set var.
fwrite($fp, $da);
Try using
fwrite($fp, $str);
And also you only need to fopen() once.
$filename = 'number.txt';
$content = (int) file_get_contents($filename);
$content++;
var_dump($content);
file_put_contents($filename, $content);
You have to create that file number.txt and insert there 0 as file content, then your script should work every time.
You are reading the contents into the variable $fgc, but you're trying to use $cont to represent that value, which is uninitialized. So your settype call is going to cast that to 0. Instead, try:
$fgc = file_get_contents('number.txt');
settype($fgc, "integer");

Php writing in file

I have this code:
$file = fopen($_SERVER['DOCUMENT_ROOT'].'crawl.txt', 'w+');
$time1 = microtime(true);
......
$time2 = microtime(true);
$time = $time2-$time1;
$text = "Training id: ".$this->realIdTraining." Time: ".$time."\r\n";
fwrite($file, $text);
fclose($file);
sleep(5);
I catch this error: Warning: fwrite(): 120 is not a valid stream resource
Any ideas what can I do?
Guys: Have to add that first row written correctly.(!!!)
test for permission to open the file for writing
$file = fopen($_SERVER['DOCUMENT_ROOT'].'/crawl.txt', 'w+');
if(!$file)
{
echo 'cannot write to file';
}
else
{
$time1 = microtime(true);
...
$time2 = microtime(true);
$time = $time2-$time1;
$text = "Training id: ".$this->realIdTraining." Time: ".$time."\r\n";
fwrite($file, $text);
fclose($file);
sleep(5);
}
This should work, if the code beetween ... and $this->realIdTraining exists somewhere
Also, verify first if the file exists , and others, like write permissions, if needed.
<?php
$file = fopen($_SERVER['DOCUMENT_ROOT'].'/crawl.txt', 'w+');
$time1 = microtime(true);
...
$time2 = microtime(true);
$time = $time2-$time1;
$text = "Training id: ".($this->realIdTraining)." Time: ".$time."\r\n";
fwrite($file, $text);
fclose($file);
sleep(5);
?>

Compare domains that read from file in php

I have a txt file which contains domains and ips looks like this
aaa.bbb.com 8.8.8.8
bbb.com 2.2.2.2
...
...
..
How do I replace bbb.com to 3.3.3.3 but do not change aaa.bbb.com?
Here is part of my function, but not working at all.
First part I search for the match domain by reading it line by line from file
after I got the matched record ,delete it.
Second part I write a new line into it.
$filename = "record.txt";
$lines = file($filename);
foreach($lines as $line)
if(!strstr($line, "bbb.com") //I think here is the problem core
$out .= $line;
$f = fopen($filename, "w");
fwrite($f, $out);
fclose($f);
$myFile = "record.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "bbb.com\n 3.3.3.3\n";
fwrite($fh, $stringData);
fclose($fh);
after I execute my code, both aaa.bbb.com and bbb.com were deleted, how can I solve this issue?I've try "parse_url" but "parse_url" only parse url with "http://" prefix instead of a domain.
Well, sorry for the misunderstanding, this should work:
<?php
$file = "record.txt";
$search = "bbb.com";
$replace = "3.3.3.3";
$open = file_get_contents($file);
$lines = explode(PHP_EOL, $open);
$dump = "";
foreach($lines as $line){
$pos = strpos($line, $search);
if($pos === false){
echo "<b>$line</b>";
$dump .= $line.PHP_EOL;
}else{
if($pos !== 0){
$dump .= $line.PHP_EOL;
}else{
$dump .= $search." ".$replace.PHP_EOL;
}
}
}
$dump = substr($dump,0,-1);
file_put_contents($file, $dump);
?>
The easiest solution I can think of is to use substr($line,0,7) == 'bbb.com' instead of your strstr comparison.

Help writing to two files simultaneously in PHP?

In the script below, I try to write in the same time in two files, but don't perform. How I can do it ?
$filename1 = "guestbook.doc" ;
$filename2 = "cour.doc" ;
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = stripslashes(nl2br(htmlentities($_POST['message'])));
$d = date ( "d/m/Y H:i:s" )
$handle1 = fopen($filename1, "w+");
$handle2 = fopen($filename2, "a+");
if ($handle1 && $handle2) {
fwrite($handle1, "<b>$name</b> "." - $d<br>$message<br><hr>\n");
fwrite($handle2, "<b>$name</b> ".$email." - $d<br>$message<br>\n");
}
if ($handle1) {
fclose($handle1);
}
if ($handle2) {
fclose($handle2);
}
then
{
header('Location: contact.php?' . http_build_query($_POST));
}
?>
One thing I do notice is that is kinda odd is :
then
{
header('Location: contact.php?' . http_build_query($_POST));
}
then is not a valid control structure. It's if/elseif/else.
writing to a file in PHP is procedural it will wait for handle1 to be written before moving onto handle2. It will not write them at the same time. There must be an error occurring or its not getting inside the if statement if($handle1 && $handle2) . It possibly cannot open those files for writing due to permission problems? are there any errors at all?
Try replacing that if statement with something like this and see if it breaks?
if (is_writable($filename1) or die ("Can not write to ".$filename1)) {
fwrite($handle1, "<b>$name</b> "." - $d<br>$message<br><hr>\n");
}
if (is_writable($filename2) or die ("Can not write to ".$filename2)) {
fwrite($handle2, "<b>$name</b> "." - $d<br>$message<br><hr>\n");
}
Just write one under another it will work perfect.
<?php
$filename = "guestbook.doc" ;
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = stripslashes(nl2br(htmlentities($_POST['message'])));
$d = date ( "d/m/Y H:i:s" )
$handle1 = fopen($filename, "w+");
$size = filesize($filename);
fwrite($handle, "<b>$name</b> "." - $d<br>$message<br><hr>\n");
$text = fread($handle, $size);
fclose($handle);
$filename = "cour.doc" ;
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = stripslashes(nl2br(htmlentities($_POST['message'])));
$d = date ( "d/m/Y H:i:s" )
$handle = fopen($filename1, "w+");
$size = filesize($filename1);
fwrite($handle, "<b>$name</b> ".$email." - $d<br>$message<br>\n");
$text = fread($handle, $size);
fclose($handle);
?>

Write to specific line in PHP

I'm writing some code and I need to write a number to a specific line. Here's what I have so far:
<?php
$statsloc = getcwd() . "/stats/stats.txt";
$handle = fopen($statsloc, 'r+');
for($linei = 0; $linei < $zone; $linei++) $line = fgets($handle);
$line = trim($line);
echo $line;
$line++;
echo $line;
I don't know where to continue after this. I need to write $line to that line, while maintaining all the other lines.
you can use file to get the file as an array of lines, then change the line you need, and rewrite the whole lot back to the file.
<?php
$filename = getcwd() . "/stats/stats.txt";
$line_i_am_looking_for = 123;
$lines = file( $filename , FILE_IGNORE_NEW_LINES );
$lines[$line_i_am_looking_for] = 'my modified line';
file_put_contents( $filename , implode( "\n", $lines ) );
This should work. It will get rather inefficient if the file is too large though, so it depends on your situation if this is a good answer or not.
$stats = file('/path/to/stats', FILE_IGNORE_NEW_LINES); // read file into array
$line = $stats[$offset]; // read line
array_splice($stats, $offset, 0, $newline); // insert $newline at $offset
file_put_contents('/path/to/stats', join("\n", $stats)); // write to file
I encountered this today and wanted to solve using the 2 answers posted but that didn't work. I had to change it to this:
<?php
$filepathname = "./stats.txt";
$target = "1234";
$newline = "after 1234";
$stats = file($filepathname, FILE_IGNORE_NEW_LINES);
$offset = array_search($target,$stats) +1;
array_splice($stats, $offset, 0, $newline);
file_put_contents($filepathname, join("\n", $stats));
?>
Because these lines don't work since the arg of the array is not an index:
$line = $stats[$offset];
$lines[$line_i_am_looking_for] = 'my modified line';
Had to add that +1 to have the new line under the searched text.

Categories