The opendir() function opens a directory handle.
PHP opendir() Function has the following syntax.
opendir(path,context);
Parameter | Is Required | Description |
---|---|---|
path | Required. | Directory path to be opened |
context | Optional. | Context of the directory handle. |
PHP opendir() Function returns the directory handle resource on success. FALSE on failure.
Open a directory, read its contents, then close:
<?php/* w ww . j a va 2 s . c o m*/
$dir = "/images/";
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "\n";
}
closedir($dh);
}
}
?>
The following code shows how to open a directory, list its files, reset directory handle, list its files once again, then close.
/*from w w w . j ava2 s . c o m*/
<?php
$dir = "/images/";
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
// List files in images directory
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
}
rewinddir();
// List once again files in images directory
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
}
closedir($dh);
}
}
?>