Page 1 of 1

Is closedir() NEEDED??

Posted: Tue Jun 06, 2006 11:49 am
by danselstudios
ok, i'm using opendir() and readdir() to make a dynamic menu from my directories.

DO I really need to use closedir() to close the directory????
what happens if i don't close it?????

Code: Select all

<?php
if ( $dir = opendir(".") ){
	while (false !== ($file = readdir($dir)) ){
		if ( $file != "." && $file != ".." ){
			if ( is_file($file) ){
				$files[] = $file;
			}
			else {
				$dirs[] = $file.'/';
			}
		}
	}
	if($dirs) {
		natcasesort($dirs);
		foreach($dirs as $dir) {
		     $dir = trim($dir, "./");
		     echo '<tr><td class="subtitle">'.$dir.'</td></tr>';
		}
   	}
   	if($files) {
                natcasesort($files);
		foreach ($files as $file) {
		     echo '<tr><td><a href="'.$dir.'/'.$file.'">'.$file.'</a></td></tr>';
		}
	}
        // closedir($dir);  <---- see, if i use it I always get an argument error. so i tried it without the closedir() and it works just fine. but i don't know if that safe or not.
}
?>

Posted: Tue Jun 06, 2006 12:01 pm
by feyd
Closing resources is always a good idea and is considered good coding practice. This stems from the days where memory leaks could easily happen. They still do happen, but with less frequency than what has happened in previous generations of software.