Master PHP’s rewinddir(): Reset Directory Handles Efficiently

This article explains the PHP rewinddir() function, covering its syntax, a practical example of resetting a directory handle to reread files, and important usage notes such as its limitation to opened directory handles and its lack of return value.

php Courses
php Courses
php Courses
Master PHP’s rewinddir(): Reset Directory Handles Efficiently

In PHP, when iterating over directories you often need to reset the directory handle, and the rewinddir() function is very useful for this purpose. Below we examine its syntax and usage considerations.

rewinddir() Function Basic Syntax

void rewinddir ( resource $dir_handle )

The function takes a directory handle as its parameter and resets the handle’s position to the beginning of the directory, allowing you to traverse the files from the start again.

rewinddir() Function Usage Example

$dir = opendir('/path/to/directory');
if ($dir) {
    while (($file = readdir($dir)) !== false) {
        echo $file . "
";
    }
    rewinddir($dir);
    while (($file = readdir($dir)) !== false) {
        echo $file . "
";
    }
    closedir($dir);
}

In this example we open a directory, read its files with readdir(), then call rewinddir() to reset the handle and read the files again.

Note that rewinddir() can only be used with an opened directory handle, not a file handle, and it does not return any value; it simply resets the position.

Summary

The rewinddir() function is a handy PHP function for resetting a directory handle to the start, enabling flexible file operations when traversing directories.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPdirectory handlingrewinddirfile iteration
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.