Is closedir() NEEDED??

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
danselstudios
Forum Newbie
Posts: 24
Joined: Sat Jun 03, 2006 10:47 am
Location: Corona, CA

Is closedir() NEEDED??

Post 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.
}
?>
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
Post Reply