Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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);
like image 465
Rosamunda Avatar asked Nov 30 '22 15:11

Rosamunda


1 Answers

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.

like image 116
deceze Avatar answered Dec 06 '22 15:12

deceze