Filesystem Functions
Filesystem function reference. Two layers — high-level helpers and low-level streaming.
One-shot read & write
| Function | Does |
|---|---|
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
| Function | Does |
|---|---|
fopen($path, $mode) | Open. Returns resource. |
fread / fwrite / fgets / fputs | Read/write. |
fgetcsv / fputcsv | CSV. |
fseek / ftell / rewind / feof | Cursor control. |
fflush / fclose | Flush / close. |
flock($fh, LOCK_EX) | Advisory locking. |
Filesystem ops
| Function | Does |
|---|---|
file_exists($p) / is_file / is_dir | Predicates. |
is_readable / is_writable / is_executable | Permissions 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 / filectime | Metadata. |
realpath / dirname / basename / pathinfo | Path manipulation. |
chmod($p, 0644) / chown / chgrp | Permissions / 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__))
PascalCase; long name.
Discussion
Loading…