Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PHP close the file after the file handler is garbage collected?

Tags:

If I have a short function that opens a file and reads a line, do I need to close the file? Or will PHP do this automatically when execution exits the function and $fh is garbage collected?

function first_line($file) {     $fh = fopen($file);     $first_line = fgets($fh);     fclose($fh);     return $first_line; } 

could then be simplified to

function first_line($file) {     return fgets(fopen($file)); } 

This is of course theoretical right now, as this code doesn't have any error handling.

like image 529
Znarkus Avatar asked Aug 27 '12 13:08

Znarkus


People also ask

How do you close a file in PHP?

The fclose() function closes an open file pointer. Note: The file must have been opened by fopen() or fsockopen().


2 Answers

PHP automatically runs the resource destructor as soon as all references to that resource are dropped.

As PHP has a reference-counting based garbage collection you can be fairly sure that this happens as early as possible, in your case as soon as $fh goes out of scope.

Before PHP 5.4 fclose didn't actually do anything if you tried to close a resource that had more than two references assigned to it.

like image 114
NikiC Avatar answered Jun 13 '23 21:06

NikiC


Yes. Resources are released automatically when they go out of scope. To wit:

<?php  class DummyStream {      function stream_open($path, $mode, $options, &$opened_path) {     echo "open $path<br>";         return true;     }      function stream_close() {         echo "close<br>";         return true;     } }  stream_wrapper_register("dummy", "DummyStream");  function test() {     echo "before open<br>";     fopen("dummy://hello", "rb");     echo "after open<br>"; }  test();  ?> 

Output:

before open open dummy://hello close after open 

The file handle is released as soon as fopen() returns, as there's nothing here capturing the handle.

like image 32
cleong Avatar answered Jun 13 '23 22:06

cleong