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);
?>
Related
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);
I've a problem with a PHP script that creates some csv file.
The PHP script is the following:
<?php
$inputFile = "/var/www/vhosts/pecso.it/httpdocs/test/export30gg.txt";
$csvData = file_get_contents($inputFile);
$rows = explode(PHP_EOL, $csvData);
$rowsArray = array();
foreach ($rows as $row) {
$rowsArray[] = str_getcsv($row);
}
$csvFileName = "/var/www/vhosts/pecso.it/httpdocs/graphs/export30gg.csv";
if (file_exists($csvFileName)){
unlink($csvFileName);
}
$csvFile = fopen($csvFileName, "w");
$csvFileForGraph = fopen($csvFileNameForGraph, "w");
for ($i = 0; $i < count($rowsArray); $i++) {
$dateTime = DateTime::createFromFormat('d/m/Y', $rowsArray[$i][0]);
$d = $dateTime->format('Y-m-d');
$rowsArray[$i][0] = $d;
$rowForGraph = $rowsArray[$i];
unset($rowForGraph[1]);
$row = implode(',',$rowsArray[$i]);
$rowForGraph = implode(',',$rowForGraph);
file_put_contents($csvFileName, $row.PHP_EOL , FILE_APPEND);
}
fclose($csvFileName);
?>
This script works correctly and csv file export30gg.csv is correctly created but, every time I run this script, I've the following error:
fclose() expects parameter 1 to be resource
Can you help me, please?
flose() accepts parameter as file pointer resource which will be found while code execution for example in your case it is $csvFile = fopen($csvFileName, "w");
So, it should be
fclose($csvFile);
and not the fclose($csvFileName);
It should be like
fclose($csvFile);
because you've stored recourse link in $csvFile, not in $csvFileName
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");
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);
?>
Done
<?php
define('FILE_NAME', 'list.dat');
define('MAX_BREAK', 30);
function write($file, $ip, $time)
{
fwrite($file, $ip . '|' . $time . "\n");
}
$new_ip = /*$REMOTE_ADDR*/ $_SERVER['REMOTE_ADDR'];
$file = fopen(FILE_NAME, 'w+');
flock($file, LOCK_EX | LOCK_SH);
$array = file(FILE_NAME, FILE_IGNORE_NEW_LINES);
$contains = false;
foreach ($array as $record)
{
$values = explode('|', $record);
$ip = $values[0];
$time = $values[1];
if ($ip == $new_ip)
{
$time = time();
$contains = true;
}
if (time() - $time < MAX_BREAK)
write($file, $ip, $time);
}
if (!$contains)
write($file, $new_ip, time());
flock($file, LOCK_UN);
fclose($file);
?>
$array is empty, but it shouldn't because file contains one line.
Any ideas why?
Because list.dat is empty.
fopen with w+
'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
If the file command is returning false, it means file() failed. I think it might be failing because you already have it locked with your flock() call. The file() function does not need to be preceded by an fopen().
Using flock() you aquire an exclusive lock on the file and after that you want to read it. That doesn't work. A shared lock will probably be enough (no one can alter the file while it's locked).
flock($file, LOCK_EX | LOCK_SH);
becomes
flock($file, LOCK_SH);