PHP Directory

Beginner
8 min read
Updated: Nov 2026
3 examples
Navigate & list folders

Definition and Usage

Directory functions in PHP let a script find out where it is running, move to another folder, and read what a folder contains. They are the base for file browsers, upload managers, backup scripts, and any code that needs to walk through files.

Use getcwd() to read the current working directory and chdir() to change it. Relative paths such as data/file.txt are resolved from that directory, so know where it points before you open files.

To list a folder, call scandir() for a ready-made sorted array. For one entry at a time, use opendir(), readdir(), and closedir(), with rewinddir() to start over. The dir() function wraps the same handle in a Directory object.

This page explains the ideas. The Directory Functions index lists all 9 function guides.

Pick the right listing tool.

Use scandir() for small folders where an array is enough. Use opendir() with readdir() when a folder may hold thousands of files and you want to process them one by one.

Skip . and .. and use !== false.

Listings include . and ... Loop with readdir($handle) !== false, not a bare truthy check, so an entry named 0 is not lost.

chroot() has hard limits.

chroot() changes the root directory of the process. It needs root privileges, does not exist on Windows, and is not available in most web server SAPIs, so treat it as a CLI-only tool. For web code, keep files under a fixed base folder and validate every path instead.

PHP Syntax

The usual locate, change, and list pattern:

PHP
$cwd = getcwd();                        // string or false
chdir(__DIR__ . '/data');               // true on success, false on failure

$names = scandir('data');               // sorted array, includes . and ..

$handle = opendir('data');              // resource handle or false
while (($entry = readdir($handle)) !== false) {
    echo $entry, PHP_EOL;               // one entry per call
}
rewinddir($handle);                     // go back to the first entry
closedir($handle);                      // release the handle

$d = dir('data');                       // Directory object
while (false !== ($entry = $d->read())) {
    echo $entry, PHP_EOL;
}
$d->close();

Core Ideas

What to remember when you work with directories in PHP:

IdeaFunctionRemember
Where am I?getcwd()Returns the working directory as a string, or false on failure
Movechdir()Changes the working directory; relative paths now start there
Change rootchroot()Needs root privileges; not on Windows; CLI, CGI, and embed only
Open handleopendir() / closedir()Open before reading and always close when done
Read entriesreaddir() / rewinddir()One entry per call, no guaranteed order; loop with !== false
Object styledir()Returns a Directory with read(), rewind(), and close()
Array listingscandir()Sorted array including . and ..; false on failure

PHP Examples

Three short scripts that show how directories work in PHP. Each one assumes the script sits in a folder named app that has a data subfolder containing a.txt, b.txt, and notes.md.

Example 1 — Working directory

Read the current directory with getcwd(), move into a subfolder with chdir(), and go back.

PHP
<?php
$start = getcwd();
echo "Start: ", basename($start), PHP_EOL;

if (chdir(__DIR__ . '/data')) {
    echo "Now in: ", basename(getcwd()), PHP_EOL;
}

chdir($start);
echo "Back in: ", basename(getcwd()), PHP_EOL;
?>
chdir() Tutorial

How It Works

  1. getcwd() returns the full path of the current directory; basename() keeps only the last folder name for a short output.
  2. chdir() moves into data and returns true, so the if block runs.
  3. Saving $start first lets you return with chdir($start) so later relative paths still work.

Example 2 — scandir vs opendir and readdir

List the same folder two ways: scandir() in one call, and opendir() with readdir() and closedir() in a loop.

PHP
<?php
$path = __DIR__ . '/data';

$names = array_diff(scandir($path), ['.', '..']);
echo "scandir: ", implode(', ', $names), PHP_EOL;

$handle = opendir($path);
$found  = [];
while (($entry = readdir($handle)) !== false) {
    if ($entry === '.' || $entry === '..') {
        continue;
    }
    $found[] = $entry;
}
closedir($handle);

sort($found);
echo "readdir: ", implode(', ', $found), PHP_EOL;
?>

How It Works

  1. scandir() returns a sorted array in one call; array_diff() removes . and ...
  2. opendir() opens a handle, and readdir() returns one entry per call until it returns false. The !== false check keeps entries such as 0.
  3. closedir() releases the handle. Because readdir() has no guaranteed order, the script calls sort() before printing.

Example 3 — dir() object and rewind

Use dir() to get a Directory object, read it with read(), start over with rewind(), and finish with close().

PHP
<?php
$d = dir(__DIR__ . '/data');
echo get_class($d), PHP_EOL;

function countFiles(Directory $d): int
{
    $count = 0;
    while (false !== ($entry = $d->read())) {
        if ($entry !== '.' && $entry !== '..') {
            $count++;
        }
    }
    return $count;
}

echo "First pass: ", countFiles($d), PHP_EOL;

$d->rewind();
echo "After rewind: ", countFiles($d), PHP_EOL;

$d->close();
?>
dir() Tutorial

How It Works

  1. dir() opens the folder and returns a Directory object, so get_class() prints Directory.
  2. The first loop reads every entry, so the handle is at the end. Calling rewind() moves it back to the start, and the second count gives the same result.
  3. close() releases the handle, just like closedir() does for the function style.

Next: PHP Directory Functions Index

After you know the working directory and the two listing styles, open the functions index for all 9 guides.

Start withWhy
getcwd()Find out which directory relative paths start from
chdir()Change the working directory safely
scandir()List a folder as a sorted array
opendir()Open a handle to read a folder entry by entry
readdir()Read the next entry from a directory handle
dir()Use the object style with Directory

Full list: PHP Directory Functions index (/php/directory/function).

Frequently Asked Questions

They are built-in functions for working with folders: read or change the current working directory, list the files and subfolders inside a directory, and open a directory handle you can read entry by entry.
scandir() reads the whole directory at once and returns a sorted array, which is short and simple for small folders. opendir(), readdir(), and closedir() read one entry at a time, which uses less memory on very large folders and gives you control over the loop. readdir() returns entries in no guaranteed order.
readdir() returns false when there are no more entries, but a file or folder named 0 is a valid entry whose value can look false in a loose comparison. Use while (($entry = readdir($handle)) !== false) so such names are not skipped.
getcwd() returns the current working directory as a string, or false on failure. chdir() changes it, which affects how relative paths such as data/file.txt are resolved for the rest of the script. It returns true on success and false on failure.
Every directory contains two special entries: . is the directory itself and .. is its parent. Skip them with array_diff() or an if check before you process real files.
Usually not. chroot() needs root privileges, is not available on Windows, and is not available in most web server SAPIs. It is mainly for the CLI, CGI, or embed SAPIs run by a privileged user. For web scripts, use fixed base directories and validate paths instead.

Browse every Directory function

Open the functions index for categorized guides with examples and FAQs.

Directory Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful