How to Use PHP rewinddir() to Reset a Directory Handle
This article explains the PHP rewinddir() function, its syntax, provides a complete code example for resetting a directory handle to the beginning of a directory, and highlights important usage notes for reliable file traversal in backend development.
When traversing directories in PHP, the rewinddir() function is essential for resetting the directory handle so you can iterate over the files again from the start.
Basic syntax:
void rewinddir ( resource $dir_handle )
The function accepts an opened directory handle as its argument and moves the internal pointer back to the beginning of the directory without returning any value.
Usage example:
$dir = opendir('/path/to/directory');<br/>if ($dir) {<br/> while (($file = readdir($dir)) !== false) {<br/> echo $file . "\n";<br/> }<br/> rewinddir($dir);<br/> while (($file = readdir($dir)) !== false) {<br/> echo $file . "\n";<br/> }<br/> closedir($dir);<br/>}
In this example, a directory is opened with opendir() , its contents are listed with readdir() , then rewinddir() resets the pointer, allowing the files to be listed a second time before finally closing the handle.
Important notes: rewinddir() can only be used on a directory handle that has been successfully opened; it cannot be applied to file handles. The function does not return a value—it simply resets the internal pointer.
Summary: The rewinddir() function is a useful PHP utility for resetting a directory handle to the start, enabling flexible and repeated file operations within backend scripts.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.