In PHP, should I use fclose() when using file_put_contents()? - php

I'm using the PHP function file_put_contents() to put some content into a txt file. The example in the docs doesn't finish using fclose(), should I close the file or it's not necessary?
I'm doing this:
$root = $_SERVER['DOCUMENT_ROOT'];
$log = $root.'/logs/logsContenido.txt';
$agregadoLog = "texto a agregar";
file_put_contents($log, $agregadoLog, FILE_APPEND | LOCK_EX);
And just that. I don't close anything.
Should I rather do something like:
$root = $_SERVER['DOCUMENT_ROOT'];
$log = $root.'/logs/logsContenido.txt';
$agregadoLog = "texto a agregar";
$file = file_put_contents($log, $agregadoLog, FILE_APPEND | LOCK_EX);
fclose($file);

No, you should not/cannot. file_put_contents takes care of opening the file, writing the contents, and closing the file. In fact it does not expose any handle to you which you could close even if you wanted to.

In file_put_contents, PHP handles it for you. So there is no need to fclose it.
But if you are using an handle like fopen, then you need to close it since you'll leave the file open during the entire exection of the script. Oh and also it is a good practice to close the handle once you are done with it

Related

php - Pass contents of file to function that's expecting a filename

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

Should I use flock when reading a file in PHP?

Ok so I am new to PHP and the example from the book shows that when I write to a file in php i should use flock($fp, LOCK_EX) after opening the file and then flock($fp, LOCK_UN) before closing the file. Like this:
$fp = fopen("$DOCUMENT_ROOT/order.txt", 'ab');
flock($fp, LOCK_EX);
fwrite($fp, $outputstring, strlent($outputstring));
flock ($fp, LOCK_UN);
fclose($fp);
But in the other example of how to read a file I am not sure if the author forgot to put flock() or it is not necessary to put flock() when reading a file. Here is the example:
$fp = fopen("$DOCUMENT_ROOT/order.txt", 'rb');
while (!feof($fp))
{
$order = fgets($fp, 999)
echo $order."<br/>";
}
fclose($fp);
So should I put flock() in the second example or not?
Thank you in advance.
It is only necessary to use flock if there are going to be multiple processes accessing the file at the same time.
If the code that writes to the file is only ever going to have have one copy running at any time, then you probably don't need to use flock. However if it is possible that multiple processes could try to run the code (and therefore access the file) at the same time, then you should use flock to make sure they do it one at a time.

How do I open a file called file*.txt in PHP

<?
$file = ("file*");
$fp = fopen($file, 'a') or die("can't open file");
fwrite($fp, "testing");
fclose($fp);
?>
I want "testing" to be written to a file called file2.txt, but it instead writes to file*. I know that i can just set $file to "file2.txt", but this is just hypothetical.
I don't believe that globbing works the way you have it listed here. You could use the glob() function, which returns an array of matched filenames:
array = glob("file*")
I wouldn't recommend doing this, of course, because it's often hard to know that you'll only have a single file called file2.txt in the directory. If you do know that, it's better to specify explicitly, rather than using globbing.
That said, if you wanted to do things this way, that's how I would do it.

Best way to download a file in PHP

Which would be the best way to download a file from another domain in PHP?
i.e. A zip file.
The easiest one is file_get_contents(), a more advanced way would be with cURL for example. You can store the data to your harddrive with file_put_contents().
normally, the fopen functions work for remote files too, so you could do the following to circumvent the memory limit (but it's slower than file_get_contents)
<?php
$remote = fopen("http://www.example.com/file.zip", "rb");
$local = fopen("local_name_of_file.zip", 'w');
while (!feof($remote)) {
$content = fread($remote, 8192);
fwrite($local, $content);
}
fclose($local);
fclose($remote);
?>
copied from here: http://www.php.net/fread
You may use one code line to do this:
copy(URL, destination);
This function returns TRUE on success and FALSE on failure.

php Logging Issues

Code works fine, except for the fact that there is a problem here:
//Log Events
function logEvent($newinput) {
if ($newinput !== NULL) {
// Add a timestamp to the start of the $message
$newinput = date("Y/m/d H:i:s").': '.$newinput;
$fp = fopen('log.txt', 'w');
fwrite($fp, $newinput."\n");
fclose($fp);
}
}
//Problem writing these two lines to log.txt?
//The bad, the two lines below are not on the log.txt
logEvent('Selection'.$selections[$selection]);
logEvent('Change' . $change. 'cents.');
//This line is written to a text file (log.txt), okay that's good.
logEvent('Input' . $newinput);
i think you're not appending to the file, you're rewriting it. try fopen with 'a' instead of 'w'.
You need to use the append modifier when opening the file, you've gone
fopen('log.txt', 'w');
this means that every time you call that function, the log file is getting blown out and recreated, if you instead used
fopen('log.txt', 'a');
then your new log entries will append to the file instead.
You could also look into keeping the file open for later inserts too, but there may be issues with multiple updates in other requests.

Categories