PHP fwrite doesn't update the file using the append mode - php

The following code is working but it doesn't update the contents of the file it created.
I can see that the file contents have changed (the size increased) but when I download the file from my server it's empty.
the file is chmod to 666 and its parent directory as well.
its a linux server running Apache and PHP.
I've also tried using fflush to force it to flush the contents.
<?php
header("Location: http://www.example.com");
$handle = fopen("log.txt", "a");
foreach($_POST as $variable => $value) {
fwrite($handle, $variable);
fwrite($handle, '=');
fwrite($handle, $value);
fwrite($handle, '\r\n');
}
fwrite($handle, '\r\n');
fflush($handle);
fclose($handle);
?>
what is the problem?
Thanks!

I think a good practice is to check if a file is writable with is_writable then if it can be opened by checking the value returned by fopen, by the way your code is right.
Try this:
$filename = "log.txt";
$mode = "a";
// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (!$handle = fopen($filename, $mode)) {
echo "Cannot open file ($filename)";
exit;
}
foreach($_POST as $variable => $value) {
fwrite($handle, $variable);
fwrite($handle, '=');
fwrite($handle, $value);
fwrite($handle, '\r\n');
}
fwrite($handle, '\r\n');
fflush($handle);
fclose($handle);
echo "Content written to file ($filename)";
} else {
echo "The file $filename is not writable";
}

Related

PHP : Can file write mode lose data and size?

I have a problem with my logs file, in the past, I used fopen($file, "w+"); with the w+ mode to generate and I wrote on the file, and I used fwrite function to write data and header.
With the time I changed the mode to fopen($file, "a"); and I use the fputs function to write the header, and fwrite for writing the data, but right after that the size of logs is being Vvery small compared to old files, and I think that I lose the data.
My question: I think that the write mode, block the code (sometimes) to write on the file, is that can be true? if not, are there any other things I need to check to fix the problem?
Past code :
if (file_exists($file)) {
$handle = fopen($file, "a+");
fwrite($handle, $record);
fclose($handle);
} else {
$handle = fopen($file, "w+");
$header = 'Name;Last Name;Age;User;Comment';
fwrite($handle, $header);
fwrite($handle, $record);
fclose($handle);
}
New Code :
if(!file_exists($file)) {
$handle = fopen($file, 'a');
$headers = ['Name', 'Last Name', 'Age', 'User', 'Comment'];
fputs($handle, implode($headers, ';')."\n");
fwrite($handle, $record);
fclose($handle);
} else {
$handle = fopen($file, "a+");
fwrite($handle, $record);
fclose($handle);
}
Example: On the past, the size of a day file is 71Mo, but right after the modifications the size of day file was 7Ko

PHP cron fwrite dont work

I try this:
<?php
$time = time();
$fh = fopen("cron.txt", 'a+');
fwrite($fh, $time);
echo "ok";
?>
to run on SSH:
/opt/bitnami/php/bin/php /opt/bitnami/apache2/htdocs/cron.php
and remote server:
budzinski.xyz/cron.php
on localhost it works fine, on remote server and on cron, don't
your cron command needs to modified like this-:
/opt/bitnami/php/bin/php /home/[yourcpanelname]/[your patht to the file]/cron.php
check the permissions of file is it writable or not
Try out this example and than see if you are getting any output or not
<?php
$filename = 'test.txt';
$somecontent = "Add this to the file\n";
// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file.
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($somecontent) to file ($filename)";
fclose($handle);
} else {
echo "The file $filename is not writable";
}
?>

Write and read from the same file- PHP

I am trying to write to a file and then read the data from the same file. But sometimes I am facing this issue that the file reading process is getting started even before the file writing gets finished. How can I solve this issue ? How can i make file writing process finish before moving ahead?
// writing to file
$string= <12 kb of specific data which i need>;
$filename.="/ttc/";
$filename.="datasave.html";
if($fp = fopen($filename, 'w'))
{
fwrite($fp, $string);
fclose($fp);
}
// writing to the file
$handle = fopen($filename, "r") ;
$datatnc = fread($handle, filesize($filename));
$datatnc = addslashes($datatnc);
fclose($handle);
The reason it does not work is because when you are done writing a string to the file the file pointer points to the end of the file so later when you try to read the same file with the same file pointer there is nothing more to read. All you have to do is rewind the pointer to the beginning of the file. Here is an example:
<?php
$fileName = 'test_file';
$savePath = "tmp/tests/" . $fileName;
//create file pointer handle
$fp = fopen($savePath, 'r+');
fwrite($fp, "Writing and Reading with same fopen handle!");
//Now rewind file pointer to start reading
rewind($fp);
//this will output "Writing and Reading with same fopen handle!"
echo fread($fp, filesize($savePath));
fclose($fp);
?>
Here is more info on the rewind() method http://php.net/manual/en/function.rewind.php
I have mentioned the URL through which i got the solution. I implemented the same. If you want me to copy the text from that link then here it is :
$file = fopen("test.txt","w+");
// exclusive lock
if (flock($file,LOCK_EX))
{
fwrite($file,"Write something");
// release lock
flock($file,LOCK_UN);
}
else
{
echo "Error locking file!";
}
fclose($file);
Use fclose after writing to close the file pointer and then fopen again to open it.

fwrite not writing

$fp = fopen('log.txt', 'w');
fwrite($fp, 'Missing gallery image for: ' . $row['toolbar_id'] . '\n');
The code above is not writing to the file. the $row['toolbar_id'] is a value from a for each loop. Any suggestions? There is no PHP error, as the file does open as I have debugged that part.
Try this for extra surety
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$fp = fopen('log.txt', 'ab');
if (false === $fp) {
throw new RuntimeException('Unable to open log file for writing');
}
$bytes = fwrite($fp, 'Missing gallery image for: ' . $row['toolbar_id'] . PHP_EOL);
printf('Wrote %d bytes to %s', $bytes, realpath('log.txt'));
fclose($fp);
Edit: Changed the "write" flag (w) to "append" (a) as truncating a log file doesn't sound like a great idea
https://bugs.php.net/bug.php?id=48607
there is a php bug with fwrite and ftp which means the last chunks of files sometimes dont get written when fclose is called directly after fwrite
putting a sleep(1); before fclose fixes the issue, or in your case logging to a file before fclose can also stop it
posting for future reference!
<?php
$filename = 'log.txt';
$somecontent = "Missing gallery image for: ";
if($row['toolbar_id'] != "")
{
$somecontent .= $row['toolbar_id'];
}
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($somecontent) to file ($filename)";
fclose($handle);
} else {
echo "The file $filename is not writable";
}
?>
Try this code... !!

File Handling using PHP

Can anyone tell the method to modify/delete the contents of a text file using PHP
Using file_put_contents:
file_put_contents($filename, 'file_content');
If you want to append to the file instead of replacing it's contents use:
file_put_contents($filename, 'append_this', FILE_APPEND);
(file_out_contents is the simpler alternative to using the whole fopen complex.)
By using fopen:
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'w')) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote to file ($filename)";
fclose($handle);
}
Write "" to a file to delete its contents.
To delete contents line by line use:
$arr = file($fileName);
unset($arr[3]); // 3 is an arbitrary line
then write the file contents. Or are you referring to memory mapped files?
There are number of ways to read files. Large files can be handled very fast using
$fd = fopen ("log.txt", "r"); // you can use w/a switches to write append text
while (!feof ($fd))
{
$buffer = fgets($fd, 4096);
$lines[] = $buffer;
}
fclose ($fd);
you can also use file_get_contents() to read files. its short way of achieving same thing.
to modify or append file you can use
$filePointer = fopen("log.txt", "a");
fputs($filePointer, "Text HERE TO WRITE");
fclose($filePointer);
YOU CAN ALSO LOAD THE FILE INTO ARRAY AND THEN PERFORM SEARCH OPERATION TO DELETE THE SPECIFIC ELEMENTS OF THE ARRAY.
$lines = file('FILE WITH COMPLETE PATH.'); // SINGLE SLASH SHOULD BE DOUBLE SLASH IN THE PATH SOMTHING LIKE C://PATH//TO//FILE.TXT
Above code will load the file in $lines array.

Categories