Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 147 ยท Working with Files

Files and Directories

Manage files and folders in PHP - mkdir, scandir, glob, is_file and is_dir, copy, rename, unlink, file sizes and dates, realpath, temp files and recursive iteration.

Reading and Writing Files was about what's inside a file. This lesson is about the file system around it: creating and listing folders, checking whether something exists, copying, moving and deleting, reading sizes and modification times, working with paths, using temporary files, and walking a whole tree of folders.

These are everyday tasks in real applications: cleaning up old uploads, rotating log files, building an export folder, finding every .md file in a content directory (this website does exactly that). PHP's functions for them are short and mostly named after the Unix commands they mirror (mkdir, rmdir, unlink, rename, copy, touch, chmod), so they're easy to remember once you've seen them.

The examples create real files and folders on our server, inside a fresh folder for each run. Nothing survives between runs, so feel free to delete things.

Creating folders and checking what exists

mkdir($path) creates a folder. By default it creates only the last part of the path, so the parent must already exist; pass true as the third argument to create every missing level at once, like mkdir -p in a shell. The second argument is the permission mode (an octal number, 0755 is typical for folders).

To ask what's at a path, use these checks. All of them return bool:

Function True when the path...
file_exists($p) exists, file or folder
is_file($p) exists and is a regular file
is_dir($p) exists and is a folder
is_readable($p), is_writable($p) can be read / written by this process
is_link($p) is a symbolic link
PHP Creating folders and checking paths

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

mkdir() with true creates storage, exports, 2026 and 10 in one call. The table shows that file_exists() is true for both a folder and a file, which is why you usually want the more specific is_file() or is_dir(). Calling mkdir() on a folder that already exists emits a warning (mkdir(): File exists) and returns false, so the !is_dir() check before it is the normal pattern.

PHP caches the results of is_file(), filesize(), filemtime() and similar functions within a request. If another process (or your own touch() with a past date) changes a file and you need the fresh answer, call clearstatcache() first. Functions like unlink() and rename() clear the cache for you.

Listing a folder: scandir and glob

scandir($dir) returns every entry in a folder as an array, sorted alphabetically. It always includes the special entries . (the folder itself) and .. (its parent), which you'll nearly always want to remove:

PHP Listing a folder with scandir and glob

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice the sort order: Alps.JPG comes first because uppercase letters sort before lowercase ones in byte order. Also notice that array_diff() keeps the original keys, so $entries starts at key 2; that's harmless for implode() and foreach, but use array_values() if you need a clean list.

glob($pattern) matches names with shell-style wildcards and returns full paths:

  • * matches any number of characters, ? exactly one, [abc] one of the listed characters;
  • {jpg,png} lists alternatives, but only with the GLOB_BRACE flag (available on Linux and macOS, so check before relying on it on other systems);
  • GLOB_ONLYDIR returns only folders.

Matching is case-sensitive on Linux, which is why *.jpg doesn't find Alps.JPG. glob() returns an empty array when nothing matches, and results are sorted unless you pass GLOB_NOSORT. With GLOB_BRACE, each alternative is matched in turn, so the output lists the jpg matches, then JPG, then png.

Copying, moving and deleting

Function Does Notes
copy($from, $to) Copies a file Overwrites $to if it exists; not for folders
rename($from, $to) Moves or renames a file or folder Overwrites a target file; works across folders
unlink($path) Deletes a file Not for folders; there's no trash can
rmdir($path) Deletes a folder Only if it's empty
touch($path, $time) Creates an empty file or updates its modification time
chmod($path, 0644) Changes permissions Unix-style; mostly ignored on Windows

All of them return true on success and false (plus a warning) on failure.

PHP Copy, rename and delete

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

rename() does double duty as "move": the second call moves the backup into the archive folder. The first rmdir() returns false because the folder still contains a file (the @ hides the Directory not empty warning only because the demo prints the result instead). After unlink() empties it, rmdir() succeeds. listTree() is a small recursive function; you'll see the built-in way to walk a tree further down.

unlink() and rmdir() delete permanently. Before deleting a path that comes from a variable, make sure it really points inside the folder you mean: an empty or wrong variable has wiped out more than one server. The realpath() check in the next section is the standard guard.

File information: size, dates, names

filesize($path) returns the size in bytes, filemtime($path) the time of the last modification as a Unix timestamp (seconds since 1970), and stat($path) returns everything at once. For paths, basename(), dirname() and pathinfo() take a path string apart without touching the disk:

PHP Sizes, dates and path parts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The file is 2400 bytes (100 lines of 24 bytes), which humanSize() shows as 2.3 KB. touch() set its modification time to a fixed date so the output is stable; normally filemtime() returns when the file was last written. Look at pathinfo(): for sales-q3.final.csv, the extension is only the part after the last dot (csv), and filename is sales-q3.final. (On a real server dirname is the full folder path; our editor shortens paths in the output.)

Comparing filemtime() with a timestamp is how cleanup jobs find old files, for example "delete exports older than 30 days". Dates and Times covers strtotime() and dates in depth.

realpath and staying inside a folder

realpath($path) resolves ., .. and symbolic links and returns the canonical absolute path, or false if the path doesn't exist. That makes it the tool for checking that a path built from user input really stays inside an allowed folder:

PHP Keeping user paths inside a folder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

../secret.env exists, but its real path is outside docs/, so it's rejected; nope.txt doesn't exist, so realpath() returns false. ./terms.txt resolves to the same file as terms.txt and is allowed. Comparing against $base . DIRECTORY_SEPARATOR (and not just $base) prevents a sibling folder called docs-private from passing the check. Secure Coding covers path traversal attacks in more detail.

Temporary files

When you need a scratch file, such as an export being assembled or a download being processed, don't invent a name in your project folder. Use the system's temp folder:

  • sys_get_temp_dir() returns the temp folder (/tmp on Linux);
  • tempnam($dir, $prefix) creates a new, empty file with a unique name in $dir and returns its path. You must delete it yourself;
  • tmpfile() returns an open handle to a temp file that's deleted automatically when it's closed or the script ends.
PHP tempnam and tmpfile

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The temp file names are random (like export-Ab3xQ9), which is why the example checks the prefix instead of printing the name. tmpfile() cleans up after itself: the file exists while the handle is open and is gone after fclose(). For data that fits in memory, the php://temp stream from Streams and Wrappers avoids the disk entirely.

Walking a folder tree recursively

To process every file in a folder and all its subfolders, combine two classes from the SPL: RecursiveDirectoryIterator knows how to read one folder and descend into subfolders, and RecursiveIteratorIterator flattens that tree into one simple loop. Each item is an SplFileInfo object with methods like getFilename(), getExtension(), getSize() and getPathname().

PHP Finding files in a whole tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The loop finds the three .md files at every depth and skips _track.yml and notes.txt. Two details matter:

  • FilesystemIterator::SKIP_DOTS leaves out the . and .. entries. Without it you'd have to filter them yourself.
  • The order isn't guaranteed. Directory iterators return entries in whatever order the file system stores them, which differs between systems, so the example sorts the results. scandir() and glob() sort for you; iterators don't.

By default RecursiveIteratorIterator yields only files (it uses LEAVES_ONLY mode). Pass RecursiveIteratorIterator::SELF_FIRST to get folders as well, before their contents, or CHILD_FIRST to get contents before their folder. CHILD_FIRST is exactly the order you need to delete a whole tree, since each folder is empty by the time you reach it:

PHP
function deleteTree(string $dir): void
{
    $items = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS),
        RecursiveIteratorIterator::CHILD_FIRST
    );
    foreach ($items as $item) {
        $item->isDir() ? rmdir($item->getPathname()) : unlink($item->getPathname());
    }
    rmdir($dir);
}

For a single folder without recursion, new FilesystemIterator($dir) gives you the same SplFileInfo objects without the dots.

More filesystem functions

PHP's filesystem toolbox is larger than the handful of functions above. This section is a tour of the rest, grouped by what they are for.

  • filetype($path) returns file, dir, link, fifo, char, block or unknown. It does not follow symbolic links, so a link reports link.
  • stat($path) returns an array with size, timestamps, permissions, owner and more; lstat($path) does the same for the link itself instead of its target. fstat($handle) reads the same record from an open file handle, which is useful when the file may be renamed or deleted while you work.
  • symlink() creates a symbolic link, link() creates a hard link (another name for the same data; the nlink field counts them), readlink() shows where a symbolic link points and is_link() tests for one. On Windows creating symlinks needs special privileges.
  • fileatime(), filectime() and filemtime() return the access, metadata-change and modification times. Note that filectime is not the creation time on Linux. Results are cached, so call clearstatcache() when a file may have changed during the request.
  • fileowner(), filegroup() and fileperms() read ownership and mode. chown() and chgrp() change them, but only a privileged process can give a file away, so they usually fail in a normal web request. chmod() is the one you will actually use, and umask() controls the default permissions of new files.

Reading to the output and wildcard matching

  • fpassthru($handle) copies everything from the current position to the output and returns the byte count. readfile($path) is the shortcut that opens, passes through and closes. Both stream without loading the file into memory, which is why they are used for downloads (see HTTP Headers and Redirects).
  • fnmatch($pattern, $name) matches a name against a shell pattern (*, ?, [a-z]) without touching the disk. Flags add FNM_CASEFOLD (ignore case) and FNM_PATHNAME (so * does not match a slash). It is perfect for allow-lists such as "skip everything matching *.log".

Disk space, pipes and temporary files

  • disk_free_space($dir) and disk_total_space($dir) report bytes for the filesystem that holds the directory: useful before accepting a big upload or writing a backup.
  • popen($command, 'r') runs a shell command and gives you a pipe you can read with fgets(); close it with pclose(), which returns the exit status. For anything with user input prefer proc_open() with an argument array, and read Secure Coding about escapeshellarg().
  • tmpfile() creates an anonymous temporary file that is deleted when the handle is closed or the script ends, as opposed to tempnam(), which leaves a named file you must remove yourself.
  • is_uploaded_file($path) is true only for a file that arrived through the current request's upload, and move_uploaded_file() performs the same check before moving it. Always use them for $_FILES['x']['tmp_name'], as explained in File Uploads.
PHP A tour of the filesystem helpers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

chown(), chgrp() and the like are not shown running because the sandbox user cannot give files away. On a server they are used by deployment scripts running as root, almost never by web requests.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does scandir($dir) return for a folder that contains only a.txt?

    scandir always includes the . and .. entries and returns names, not full paths. Remove the dots with array_diff($list, ['.', '..']).
  2. 2. A folder still contains one file. What does rmdir() on it do?

    rmdir only deletes empty folders. Delete the contents first, for example with a CHILD_FIRST recursive iterator.
  3. 3. What is pathinfo("/data/archive.tar.gz")["extension"]?

    pathinfo treats only the part after the last dot as the extension. The filename is archive.tar.
  4. 4. Why does glob("$dir/*.jpg") miss a file named PHOTO.JPG on Linux?

    Linux file names are case-sensitive and so is glob. Use a pattern like *.{jpg,JPG} with GLOB_BRACE, or filter with strtolower(pathinfo(...)).
  5. 5. Why compare realpath($requested) against the base folder?

    A request like ../secret.env looks like it's inside docs/ but resolves outside it. Checking the resolved path blocks path traversal; realpath also returns false for paths that don't exist.

Summary

  • mkdir($path, 0755, true) creates nested folders; check is_dir() first to avoid a warning. Use is_file()/is_dir() rather than file_exists() when the type matters.
  • scandir() lists names (sorted, including . and ..); glob() matches wildcard patterns and returns paths (GLOB_BRACE, GLOB_ONLYDIR; case-sensitive on Linux).
  • copy() copies files, rename() renames or moves files and folders, unlink() deletes files, rmdir() deletes empty folders, touch() creates files or sets their time.
  • filesize(), filemtime() and stat() give file information; clearstatcache() refreshes cached results. basename(), dirname() and pathinfo() split paths without touching the disk.
  • realpath() resolves .. and links (or returns false), which lets you confirm a user-supplied path stays inside an allowed folder.
  • Use sys_get_temp_dir() + tempnam() for named temp files (delete them yourself) or tmpfile() for handles that clean up automatically.
  • RecursiveIteratorIterator + RecursiveDirectoryIterator (with SKIP_DOTS) walk a tree; sort the results yourself, and use CHILD_FIRST to delete a tree.

Next: CSV Files