iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Filesystem Functions

Filesystem function reference. Two layers — high-level helpers and low-level streaming.

One-shot read & write

FunctionDoes
file_get_contents($path)Whole file as string.
file_put_contents($path, $data, $flags = 0)Whole write; flags: FILE_APPEND, LOCK_EX.
file($path)Array of lines.
readfile($path)Stream to stdout.

Stream

FunctionDoes
fopen($path, $mode)Open. Returns resource.
fread / fwrite / fgets / fputsRead/write.
fgetcsv / fputcsvCSV.
fseek / ftell / rewind / feofCursor control.
fflush / fcloseFlush / close.
flock($fh, LOCK_EX)Advisory locking.

Filesystem ops

FunctionDoes
file_exists($p) / is_file / is_dirPredicates.
is_readable / is_writable / is_executablePermissions checks.
copy($src, $dst) / rename($a, $b) / unlink($p)Copy / move / delete.
mkdir($p, 0755, true)Create dir (recursive).
rmdir($p)Remove empty dir.
scandir($p) / glob($pattern)List directory.
filesize / filemtime / fileatime / filectimeMetadata.
realpath / dirname / basename / pathinfoPath manipulation.
chmod($p, 0644) / chown / chgrpPermissions / ownership.
tempnam(sys_get_temp_dir(), 'pre_')Unique temp file.

SplFileInfo / SplFileObject

For iterating a directory or reading a file with OO ergonomics:

PHP
foreach (new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator(__DIR__, FilesystemIterator::SKIP_DOTS)
) as $file) {
    /** @var SplFileInfo $file */
    if ($file->isFile() && $file->getExtension() === 'php') {
        echo $file->getPathname(), PHP_EOL;
    }
}
Tip: For composable filesystem code across local disk, S3, FTP, in-memory, etc., use Flysystem. Frameworks like Laravel layer their Storage facade on top of it.

Example

Example
<?php
// file_get_contents, file_put_contents, file_exists,
// fopen/fclose/fread/fwrite/fgets, glob, scandir,
// unlink, copy, rename, mkdir, rmdir.
echo 'See the file-handling lesson for runnable demos.';
Try it Yourself »

Exercise

Recursive iterator for a directory.

new (new RecursiveDirectoryIterator(__DIR__))

Test yourself

Q1. Flush+close once for atomicity by…
Q2. Composable cross-driver FS via…
Q3. For directory listing use…

Discussion

Loading…