opendir() function

The opendir() function requires a directory name and returns a directory handle. In this example, we read through the directory, examine each file for its byte size then print out into a table. The table below will update automatically as PHP test files are added to the directory.


I've thrown in the table row color alternating code from the ColorRowTest.php file --just for fun ;0)
Filename File Size
. 671
.. 346
lunchForm.html 682
rewinddir.php 2998
file7-6.txt 189
translateArray.php 2266
writeTable.php 1750
getLastMod.php 2597
fgets.php 1655
data.txt 258
file7_7.txt 7397
elseifTest.php 2461
lastLogClass.php 2416
stat.php 2772
opendir.php 3105
file.php 1176
phpinfo.php 1045
recursion.php 2115
whileTest.php 2076
popen_pclose.php 1885
getCurrentUser.php 898
fileIO.php 2387
closedir.php 1739
lunchCost.php 782

Back to Bill's PHP

Using the <pre> tag, we show the code below which produces the results shown above. The code you see below is also run "behind the scenes" in PHP above.

<?

/*
** print the current directory in a table
*/

/* BEGIN row color code */

function useColor() {
  static $ColorValue;
  
    if ($ColorValue == "#00ff00")
    {
      $ColorValue = "#ccffcc";
    }
    else
    {
      $ColorValue = "#00ff00";
  }
  return($ColorValue);
}

/* END row color code */

print("<table border=\"1\">\n");

/*
/** create a header row
*/
print("<tr>\n");
print("<th>Filename\n");
print("<th>File Size\n");
print("</tr>\n");

// open directory
$myDirectory = opendir(".");

// get each entry
while($entryName = readdir($myDirectory))
{
// get the color for this row
$RowColor = useColor();
    print("<tr>\n");
    print("<td bgcolor=\"$RowColor\">$entryName\n");
    print("<td  bgcolor=\"$RowColor\" align=\"right\">");
    print(filesize($entryName));
    print("</td>\n");
    print("</tr>\n");
}

// close the directory
closedir($myDirectory);
 print("</table>\n");
 

?>

Back to Bill's PHP