I noticed while testing two fopen() handles on one file, that the handles or channels mix, and the file contents empty when i call fread(). One handle is read, and one handle is write.
Example code:
$rh = fopen('existingfilewithcontent.txt', 'r');
$wh = fopen('existingfilewithcontent.txt', 'w');
echo fread($rh, 1000);
fclose($rh);
fclose($wh);
// file is now blank
This is tested on Linux & Windows.
I could not find anything in the PHP docs about it.
Please do not ask my why I would want two handles on one file as that is not the question.
Thankyou
Opening a file for write is destructive.
Manual says:
'w' - Open for writing only; 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.
You probably want:
'r+' - Open for reading and writing; place the file pointer at the beginning of the file.
OR
'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended.
See manual: http://php.net/manual/en/function.fopen.php
Related
how can I write into text file without erase all the existing data?
I tried this
$txt = 'srge';
$file = fopen('text.txt','w');
fwrite($file,$txt);
but it's not working, it's earse everything
Note: This will only work when you have appropriate permission for test.txt else it will say
permission denied (un-appropriate will lead to this)
Here we are using:
1. a which is for append this will append text at the end of file.
2. instead of w, flag w is for write, which will write on file without caring about you existing data in that file.
PHP code:
<?php
ini_set('display_errors', 1);
$txt = 'srge';
$file = fopen('text.txt','a');
fwrite($file,$txt);
according to php documentation:
while you are using :
'w' Open for writing only; 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.
try instead:
'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended.
Try with following code
$txt = 'srge';
$file = fopen('text.txt','a');
fwrite($file,$txt);
Writing or Appending to a File
The processes for writing to or appending to a file are the same. The difference lies in the fopen() call. When you write to a file, you should use the mode argument "w" when you call fopen():
$fp = fopen( "test.txt", "w" );
All subsequent writing will occur from the start of the file. If the file doesn't already exist, it will be created. If the file already exists, any prior content will be destroyed and replaced by the data you write.
When you append to a file, you should use mode "a" in your fopen() call:
$fp = fopen( "test.txt", "a" );
For more details please refer this : File operation example
Php Filesystem Functions
You can use this.
$content = 'any text';
$file = fopen('file.txt','a');
fwrite($file,$content);
Have you noticed i used mode a
"a" (Write only. Opens and writes to the end of the file or creates a new file if it doesn't exist)
A visitor log on one of my sites just lost all visitors. It's been working for a year and a half but all entries were lost overnight. The log page is here (if you visit one of the site pages, your information will be added to the log):
http://mykindred.com/dalton/hoax/viewlog.php
The log is kept in a text file ($filename) which should limit to $maxloglines = 300. $logline contains the new visitor to be added to the log. The code that generates the log:
$lines = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$logline .= implode("\n", array_slice($lines, 0, $maxloglines));
file_put_contents($filename, $logline);
Any suggestions as to why my log would lose its entries? Do I have a coding error?
When writing files using file_put_contents, you are essentially using a series of fopen(), fwrite() and fclose() where the file is opened with file mode w:
Open for writing only; 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.
As you do not have an exclusive lock on the file, it is possible to read the file at the point at which the file has been truncated and the file pointer placed at the start. In this case, the contents of your file() command would be empty.
Instead, you should use the option LOCK_EX to secure an exclusive lock of the file while writing:
file_put_contents($filename, $logline, LOCK_EX);
You can read more about that at in the flock() documentation.
I am making an Android application that need to be able to push files onto a server.
For this I'm using POST and fopen/fwrite but this method only appends to the file and using unlink before writing to the file has no effect. (file_put_contents has the exact same effect)
This is what I have so far
<?php
$fileContent = $_POST['filecontent'];
$relativePath = "/DatabaseFiles/SavedToDoLists/".$_POST['filename'];
$savePath = $_SERVER["DOCUMENT_ROOT"].$relativePath;
unlink($savePath);
$file = fopen($savePath,"w");
fwrite($file,$fileContent);
fclose($file);
?>
The file will correctly delete its self when I don't try and write to it after but if I do try and write to it, it will appended.
Anyone got any suggestions on overwriting the file contents?
Thanks, Luke.
Use wa+ for opening and truncating:
$file = fopen($savePath,"wa+");
fopen
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.
a+: Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
file_put_contents($savePath,$fileContent);
Will overwrite the file or create if not already exist.
read this it will help show all the options for fopen
http://www.php.net/manual/en/function.fopen.php
Found the error, i forgot to reset a string inside of my application
I would like to cut off the beginning of a large file in PHP. Use of file_get_contents() is not possible due to memory restrictions.
What is the best way to delete the first $n characters from a file?
If it is possible to do it without creating a second file, I would prefer that solution.
Update After the file has been modified, it will be used by other scripts.
If you don't have enough memory to buffer the entire file, you'll need to create two files (at least temporarily) regardless of your solution.
Look into fseek(), which allows you to go to a particular byte position within a file.
// Open the file
$filename = 'somefile.dat';
$file = fopen($filename, 'r');
// Skip the first 1 KB
fseek($file, 1024);
// Your processing goes here...
// Close the file
fclose($file);
In your case, you could open the original file for reading and the temp file for writing concurrently. Seek the original file. Loop over the original file, reading a small chunk and writing it to temp. Then rename temp to have the same name as original.
I have a file with the contents:
a:12:{s:12:"a2.twimg.com";i:1308768611;s:12:"a1.twimg.com";i:1308768611;s:12:"a0.twimg.com";i:1308768612;s:12:"a3.twimg.com";i:1308768612;s:8:"this.com";i:1308768613;s:15:"f.prototype.com";i:1308768613;s:15:"c.prototype.com";i:1308768614;s:15:"a.prototype.com";i:1308768614;s:5:"w.com";i:1308768615;s:5:"s.com";i:1308768615;s:5:"f.com";i:1308768615;s:5:"h.com";i:1308768615;}
(It's an array of domains listed on twitter.com as keys and a timestamp as values)
If I call:
unserialize(fread($recentfile, filesize("./neptune_output/recent")))
("./neptune_output/recent" is the location of the $recentfile)
It fails, but if I call unserialize with that string pasted in, it works.
I use the following code to open the file.
$recentfile = fopen("./neptune_output/recent", 'a+')
I've tried putting the fopen mode as 'c+' and 'a+b' but it won't work.
Do I need to post more code?
Why don't you just read it with file_get_contents() rather than messing about with opening it and working out the file size?
a+ means: "Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it."
If you just want to read "r" is enough:
$recentfile = fopen("./neptune_output/recent", 'r')
See http://nl2.php.net/manual/en/function.fopen.php