How to list all entries in a directory using PHP

It displays both "." and ".." entries also.

<?php
 
if ($handle = opendir('/path/to/files')) {
    echo "Directory handle: $handle\n";
    echo "Entries:\n";
 
    /* This is the correct way to loop over the directory. */
    while (false !== ($entry = readdir($handle))) {
        echo "$entry\n";
    }
 
    /* This is the WRONG way to loop over the directory. */
    while ($entry = readdir($handle)) {
        echo "$entry\n";
    }
 
    closedir($handle);
}
?>
 


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


 
Read all entries in folder photo and add them into database.
 
<?php
 
$conn=mysql_connect("localhost", "root", "") or die("PHOTO NOT IN DATABASE");
mysql_select_db('test',$conn);
 
if ($handle = opendir('photo')) {
    echo "Directory handle: $handle\n";
    echo "Entries:";
$i=0;
    /* This is the correct way to loop over the directory. */
    while (false !== ($entry = readdir($handle))) {
$i++;
 
if($i==1)
continue;
else if($i==2)
continue;
else
{
$regno=substr($entry,0,4);
$photo="photo/".$entry;
$q="INSERT INTO photo (`regno`, `photo_name`) VALUES ('$regno', '$photo')";
mysql_query($q);
        echo "<br /> $i — $entry<br />";
}
    }
 
    closedir($handle);
}
?>


 

You can leave a response, or trackback from your own site.

Leave a Reply