I've been using file_put_contents in order to create txt files inside a specified folder that has write permissions:
file_put_contents($dir.$file.'.txt', $content);
Editing my code, I made a mistake: I wrote $dir = '/../../xxx/yyy/'; (that actually doesn't exist) instead of $dir = '../xxx/yyy/'; (right directory).
Obviously, no file has been created (all other folders are read-only), but I didn't get any error message about it.
Why?
P.S.: I get other error messages on the same PHP page, but not the above one.
From the docs:
"This function returns the number of bytes that were written to the file, or FALSE on failure"
https://www.php.net/manual/en/function.file-put-contents.php
I.e use something like
$result = file_put_contents($dir.$file.'.txt', $content);
And check if it's true or not
try this
$dir = '../xxx/yyy/';
$handle = fopen($dir,'w');
fwrite($dir, "write some here");
fclose($dir);
Related
$data = json_encode($data, JSON_UNESCAPED_UNICODE);
$log = base_path()."/storage/logs/trade.log";
if ( !file_exists ($log) ) {
$data = fopen($log, "w");
}
file_put_contents($log, $data . PHP_EOL.PHP_EOL, FILE_APPEND);
I have a page use file_put_contents to record log. when my folder don't exist file, it will auto create the file and add log into it
My problem is when first time auto create file and place content into it. It comes out - Resource id #233
2nd time without crate file will be normal no any problem
anyone know how to fix this?
fopen() returns a resource.
file_put_contents() write your file and converts $data into a string (calls __toString() on the resource).
The second times, the file exists. So, the program doesn't pass into the if-condition and it writes $data that contains JSON.
To solve your problem, just remove your if block.
Documentation said :
If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.
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)
Here is a snippet of what I'm trying to do:
$file = fopen($path, "wb");
fwrite($file, $data);
fclose($file);
Simple enough.
But when I open the created file, I see 0x0D inserted before 0x0A everywhere. I understand that this will happen if I open the file without binary mode.
But I've clearly specified I want binary mode. Maybe my brain isn't functioning right or something, so.. Anyone got a solution?
It turns out, for some weird reason, the problem was with my $path. My $path value was "temp".
It would generate the file named "temp" but would refuse to open it in binary mode. Giving the file an extension like "temp.bin" or "temp.tmp" allowed it to work in binary mode.
Problem solved for now but I'm still wondering why it works like this.
Seems the problem is with the $path. Please make sure you have given the correct file path.
If you are defining the $path with a dynamic file name, use / before the file name. For example, $var = "/var/www/html/projectFolder/folderFile/". "Filename.fileformat"
If you're working with URLs in a redirection context, then the root directory ('/') refers to your domain's root. The same goes for paths for linking files or images and for include and require directives.
You're making the classic mistake of confusing data with the representation of that data.
Let's say you have a text file. If you open it in Notepad, you'll see the following:
$str = "Hello world!";
echo bin2hex($str); // output: 48656c6c6f20776f726c6421
$file = fopen($path, "wb");
$data = bin2hex($data);
fwrite($file, $data);
fclose($file);
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
The script is in myusername/public_html/item/index.php
code to save file:
$filename = $_SERVER['DOCUMENT_ROOT'].'/../data/guestbook.txt';
$filehandle = fopen($filename, 'ab+') or die("<p>Unable to create the file!</p>\n".$filename);
flock($filehandle, LOCK_EX) or die("<p>Unable to lock the file!</p>\n");
fwrite($filehandle, $new_entry) or die("<p>Unable to write to the file!</p>\n");
fclose($filehandle);
For some reason it fails on the fopen and the filename is actually ends up being literally with the /../ instead of navigating to the proper path.
What to do, what to do?
you can code like this if the php script is in the item folder and item and data are at the same level in the directory hierarchy
$savedir = '../data/';
$filename = $savedir.'guestbook.txt';
make sure apache user has the write access to the directory by "chown -R apache:apache" and "chmod 755".
Probably the " /../ " in your code is giving the error. Try removing the first forward slash.
For some reason it fails on the fopen
There is no "some reasons" in programming. There are always a certain reason.
And you have to know it.
filename is actually ends up being literally with the /../
That's exactly what you wrote, nothing to complain of.
How can I save a file in PHP to a directory higher than current?
Technically you are setting it correct.
But there can be another reason, other than wrong way of the path creation.
Yes, there always can be many reasons for the program to fail!
What to do, what to do?
Run this code and see what it says.
ini_set('display_errors',1);
error_reporting(E_ALL);
$filename = $_SERVER['DOCUMENT_ROOT'].'/../data/guestbook.txt';
file_put_contents($filename,$new_entry);
it will tell you the reason why it fails.