Wednesday, January 27, 2010

PHP : Read entry from file directory

Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem.

1. List all files in a directory
<?php

if ($handle = opendir('/path/to/files')) {
echo "Directory handle: $handle\n";
echo "Files:\n";

/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
echo "$file\n";
}

/* This is the WRONG way to loop over the directory. */
while ($file = readdir($handle)) {
echo "$file\n";
}

closedir($handle);
}
?>


2. List all files in the current directory and strip out . and ..
<?php
if ($handle = opendir('../upload/images')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
?>


If you find this useful, would you like to buy me a drink? No matter more or less, it will be an encouragement for me to go further. Thanks in advance!! =)

No comments:

Post a Comment