1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
<HTML>
<HEAD>
<TITLE>Directory routines demo</TITLE>
</HEAD>
<BODY>
<H1>Directory routines demo</H1>
<DL>
<DT>Functions demonstrated
<DD><CODE><?opendir("/path/dir")?></CODE>
<DD><CODE><?closedir()?></CODE>
<DD><CODE><?readdir()?></CODE>
<DD><CODE><?rewinddir()?></CODE>
</DL>
<P>It is often important to be able to "walk" through a directory
and do something based on the files in the directory. PHP includes
functions that will let you do just that. The first thing to
do is to open the directory. The syntax for doing that is:
<PRE>
<?$dir = opendir("/path/dir")?>
</PRE>
<P>Once opened, the <CODE>readdir($dir)</CODE> function may be used
to read entries in the directory sequentially. The first call to
<CODE>readdir($dir)</CODE> will return the first entry and the second call
the second entry, etc.
<P>The <CODE>rewinddir($dir)</CODE> function can be used to move the
directory pointer back to the beginning resulting in the next call to
<CODE>readdir($dir)</CODE> returning the first entry in the directory.
<P>And, at the end, the <CODE>closedir($dir)</CODE> function should be
called.
<P>Below is a simple example which reads the contents of the
directory in which this PHP script resides.
<P>Code:
<PRE>
<?
<? $code = "\$dir = opendir(\".\");
while(\$file = readdir(\$dir)) {
echo \"\$file<BR>\";
}
closedir(\$dir);
";
echo HTMLSpecialChars($code);
echo "?>";
?>
</PRE>
<P>Output:
<PRE>
<?eval($code);?>
</PRE>
<HR>
<P>In PHP3, there is also an object-oriented syntax for working with
directories. So, for example, the code above would be:
<PRE>
<?
<? $code = "\$dir = dir(\".\");
while(\$file = \$dir->read()) {
echo \"\$file<BR>\";
}
\$dir->close();
";
echo HTMLSpecialChars($code);
echo "?>";
?>
</PRE>
<P>Output:
<PRE>
<?eval($code);?>
</PRE>
</BODY>
</HTML>
|