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
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)
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
I have a small number of image files and text files. They have the same file name with different extensions. I need to read the image files and for each image I need to read some (tool top) text from the corresponding text file. The problem is the file open inside the "foreach( glob("inserts/*.png")" loop fails. I have output the filename and the fopen works fine. I thought it may be you are unable to open two file concurrently in PHP but I could find nothing about it when I googled
foreach( glob("inserts/*.png" ) as $filename ) {
$path="public/xml/iweb/".$filename;
$insertpath=substr($filename, 0, -3)."txt";
$myfile = fopen($insertpath, "r");
$rec=fread($myfile,filesize($insertpath));
fclose($myfile);
$name=getInnerSubstring($rec,"-");
$HTML5.="<img class='insertimage' src='".$path."' title='".$name."' onclick='insertcomponent(\"".$insertpath."\")'>";
}
One day I hope I know enough to answer questions instead of just asking them. :(
There's no reason why you shouldn't be able to open multiple files and no reason the foreach should break anything that works. My hunch is that the path you're trying to open is wrong. I suggest either debugging the code to see the variables or add an echo to see their content. You should also check if fopen() and fread() don't return some false because they failed. Good luck :)
I know you can create a temporary file with tmpfile and than write to it, and close it when it is not needed anymore. But the problem I have is that I need the absolute path to the file like this:
"/var/www/html/lolo/myfile.xml"
Can I somehow get the path, even with some other function or trick?
EDIT:
I want to be able to download the file from the database, but without
$fh = fopen("/var/www/html/myfile.xml", 'w') or die("no no");
fwrite($fh, $fileData);
fclose($fh);
because if I do it like this, there is a chance of overlapping, if more people try to download the same file at exactly the same time. Or am I wrong?
EDIT2:
Maybe I can just generate unique(uniqID) filenames like that, and than delete them. Or can this be too consuming for the server if many people are downloading?
There are many ways you can achieve this, here is one
<?php
// Create a temp file in the temporary
// files directory using sys_get_temp_dir()
$temp_file = tempnam(sys_get_temp_dir(), 'MyFileName');
echo $temp_file;
?>
The above example will output something similar to:
/var/tmp/MyFileNameX322.tmp
I know you can create a temporary file with tmpfile
That is a good start, something like this will do:
$fileHandleResource = tmpfile();
Can I somehow get the path, even with some other function or trick?
Yes:
$metaData = stream_get_meta_data($fileHandleResource);
$filepath = $metaData['uri'];
This approach has the benefit of leaving it up to PHP to pick a good place and name for this temporary file, which could end up being a good thing or a bad thing depending on your needs. But it is the simplest way to do this if you don't yet have a specific reason to pick your own directory and filename.
References:
http://us.php.net/manual/en/function.stream-get-meta-data.php
Getting filename (or deleting file) using file handle
This will give you the directory. I guess after that you are on your own.
For newer (not very new lol) versions of PHP (requires php 5.2.1 or higher) #whik's answer is better suited:
<?php
// Create a temp file in the temporary
// files directory using sys_get_temp_dir()
$temp_file = tempnam(sys_get_temp_dir(), 'MyFileName');
echo $temp_file;
?>
The above example will output something similar to: /var/tmp/MyFileNameX322.tmp
old answer
Just in case someone encounters exactly the same problem. I ended up doing
$fh = fopen($filepath, 'w') or die("Can't open file $name for writing temporary stuff.");
fwrite($fh, $fileData);
fclose($fh);
and
unlink($filepath);
at the end when file is not needed anymore.
Before that, I generated filename like that:
$r = rand();
$filepath = "/var/www/html/someDirectory/$name.$r.xml";
I just generated a temporary file, deleted it, and created a folder with the same name
$tempFolder = tempnam(sys_get_temp_dir(), 'MyFileName');
unlink($tempFolder);
mkdir($tempFolder);
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