File/Directory Manipulation With PHP
PHP Directory Function List
- opendir(String $path)
Opens up a directory handle for file/directory manipulation
- getcwd(void)
Returns the current working directory.
- readdir(resource $dir_handle)
Returns the filename of the next file in the directory.
- rewinddir ([ resource $dir_handle ] )
Returns the directory stream to the beginning of the directory.
- closedir([resource $dir_handle ])
Closes the directory.
Example(Indexing the directory):
<?php
$cur_dir = '/usr/download';
/** opens the directory handle */
$dir = opendir($cur_dir);
echo 'File Listing For : ';
echo getcwd() . '<br /><ul>';
/** goes through each files and output the filename */
while(($file = readdir($dir)) !== false){
/** do not output . and .. */
if($file != '.' && $file != '..'){
echo '<li>' . $file . '</li>';
}
}
echo '</ul>';
/** closes the directory handle */
closedir($dir);
?>
A more object oriented approach
<?php
$cur_dir = '/usr/download';
$dir = dir($cur_dir);
echo 'File Listing For : ';
echo $cur_dir . '<br /><ul>';
/** goes through each files and output the filename */
while(($file = $dir->read()) !== false){
/** do not output . and .. */
if($file != '.' && $file != '..'){
echo '<li>' . $file . '</li>';
}
}
echo '</ul>';
/** closes the directory handle */
$dir->close();
?>