The rewinddir() function is an inbuilt function in PHP which is used to rewind the directory handle. The rewinddir() function opens a directory and list its files, resets the directory handle, list its files once again, then finally closes the directory handle. The directory handle sent as a parameter to the rewinddir() function and it returns Null on success or False on failure.Â
Syntax:
rewinddir ( $dir_handle )
Parameters: The rewinddir() function accepts single parameter $dir_handle. It is a mandatory parameter which specifies the handle resource previously opened by the opendir() function.Â
Return Value: It returns Null on success or False on failure.Â
Errors And Exceptions:
- If the directory handle parameter is not specified by the user then the last link opened by opendir() is assumed by the rewinddir() function.
- rewinddir() is equivalent to a closedir(), opendir() sequence, but without obtaining a new handle.
Below programs illustrate the rewinddir() function in PHP:Â
Program 1:Â
php
<?phpÂ
// Open a directory$dir_handle = opendir("C:/xampp/htdocs/gfg");Â
// Read the contents of directorywhile(($file_name = readdir($dir_handle)) !== false) { Â Â Â Â echo("File Name: " . $file_name . "<br>");}Â
// Rewinding directoryrewinddir($dir_handle);Â
while(($file_Name = readdir($dir_handle)) !== false) { Â Â Â Â echo("File Name: " . $file_Name . "<br>");} Â
// Close directoryclosedir($dir_handle);?> |
Output:
File Name: . File Name: .. File Name: content.xlsx File Name: gfg.pdf File Name: image.jpeg File Name: . File Name: .. File Name: content.xlsx File Name: gfg.pdf File Name: image.jpeg
Program 2:Â
php
<?phpÂ
// Directory path$dir_name = "C:/xampp/htdocs/gfg";Â Â // Open directory and read the content// of directoryif (is_dir($dir_name)) {Â Â if ($dir_handle = opendir($dir_name)) {Â
    // List files in images directory    while (($file_name = readdir($dir_handle)) !== false) {      echo "File Name:" . $file_name . "<br>";    }Â
    // Rewinding the directory    rewinddir();Â
    // List once again files in images directory    while (($file_name = readdir($dir_handle)) !== false) {      echo "File Name:" . $file_name . "<br>";    }Â
    // Close the directory    closedir($dir_handle);  }}?> |
Output:
filename:. filename:.. filename:content.xlsx filename:gfg.pdf filename:image.jpeg filename:. filename:.. filename:content.xlsx filename:gfg.pdf filename:image.jpeg
