$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.
Related
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);
I'm trying to create a class that converts an array into plaintext and file. Plaintext works fine however when I try to save it as a tmpfile and share it I'm getting errors.
My controller looks like:
public method index() {
$props = ['foo'=>'bar']; //array of props;
return response()->download(MyClass::create($props);
// I've also tried using return response()->file(MyClass::create($props);
}
And my class looks like:
class MyClass
{
// transform array to plain text and save
public static function create($props)
{
// I've tried various read/write permissions here with no change.
$file = fopen(tempnam(sys_get_temp_dir(), 'prefix'), 'w');
fwrite($file, implode(PHP_EOL, $props));
return $file;
}
// I've also tried File::put('filename', implode(PHP_EOL, $props)) with the same results.
}
And I'm getting a file not found exception:
The file "Resource id #11" does not exist.
I've tried tmpfile, tempname and others and get the same exception. I've tried passing MyClass::create($props)['uri'] and I got
The file "" does not exist
Is this an error due to my env (valet) or am I doing this wrong?
Your code is mixing up usage of filenames and file handles:
tempnam() returns a string: the path to a newly created temporary file
fopen() accesses a file at a given path, and returns a "resource" - a special type in PHP used to refer to system resources; in this case, the resource is more specifically a "file handle"
if you use a resource where a string was expected, PHP will just give you a label describing the resource, such as "Resource id #11"; as far as I know, there is no way to get back the filename of an open file handle
In your create definition, $file is the result of fopen(), so is a "resource" value, the open file handle. Since you return $file, the result of MyClass::create($props) is also the file handle.
The Laravel response()->download(...) method is expecting a string, the filename to access; when given a resource, it silently converts it to string, resulting in the error seen.
To get the filename, you need to make two changes to your create function:
Put the result of tempnam(sys_get_temp_dir(), 'prefix') in a variable, e.g. $filename, before calling $file = fopen($filename, 'w');
Return $filename instead of $file
You should also add a call to fclose($file) before returning, to cleanly close the file after writing your data to it.
I have the contents of a file in a string. I need to pass this file to a function where the function is expecting the parameter to be the name of the file, not the contents. The obvious and probably simplest way to do this would be to write the contents to a temp file, then pass that file name to the function, and unlink the file once I'm finished.
However, I'm looking for a solution that doesn't involve writing the file out to the file system and then reading it back in. I've had a need for this in multiple cases, so I'm not looking for a work-around to a specific function, but more of a generic method that will work for any function expecting a file name (like file_get_contents(), for instance).
Here are some thoughts, but not sure how to pursue these yet:
Is it possible to write the contents somewhere in memory, and then
pass that to the function as a filename? Perhaps something using
php://memory.
Is it possible to write the contents to a pipe, then pass the name of the
pipe to the function?
I did a short proof-of-concept trying with php://memory as follows, but no luck:
$data = "This is some file data.\n";
file_put_contents( 'php://memory', $data );
echo file_get_contents( 'php://memory' );
Would be interested in knowing of good ways to address this. Googling hasn't come up with anything for me.
It mainly depends on what the target function does with the file name. If you're lucky, you can register your own stream wrapper:
stream_wrapper_register('demo', 'DemoStream');
$data = "This is some file data.\n";
$filename = 'demo://foo';
file_put_contents($filename, $data );
echo file_get_contents($filename);
Why not use a file in the /tmp/ directory? Like this:
<?php
$filename = '/tmp/mytmpfile';
$data = "This is some file.\n";
file_put_contents($filename, $data);
$result = file_get_contents($filename);
var_dump($result);
Well, as you say you don't want to use a file, you shouldn't use file_get_contents().
But you can achieve the same result by using stream_get_contents(), like this:
<?php
$data = "This is some file data.\n";
$handle = fopen('php://memory', 'r+'); // open an r/w handle to memory
fputs($handle, $data); // write the data
rewind($handle); // rewind the pointer
echo stream_get_contents($handle); // retrieve the contents
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 intend to save all views files generated by Codeigniter on my desktop; I need to output the views into files like home.html, single.html, page.html inside a folder. Is there an solution for this?
Actually you might return a view as data, simply assign it to a variable.
$string = $this->load->view('myfile', $data, true);
Just get this response, create a file and upload to the server (using either fwrite or ftp).
Below a quick example:
<?php
$file = '/var/www/whatever/upload_dir/file.html';
$string = $this->load->view('myfile', $data, true);
// Write the contents back to the file
file_put_contents($file, $string );
?>
Hope it helps!
You can load the view and have it returned as a string by supplying a third parameter (boolean TRUE) while calling $this->load->view(). From there, you can call file_put_contents() to write the string into a file.
$view_string = $this->load->view('some_view', '', TRUE);
file_put_contents('filename', $view_string);
You can also use write_file() supplied by CodeIgniter File Helper to write the string to a file.