PHP File Handling
PHP's file functions are global and come in two layers — high-level helpers that work in one call, and low-level fopen/fread/fclose handles for streaming.
Read everything at once
PHP
$text = file_get_contents('hello.txt');
echo $text;
Write everything at once
PHP
file_put_contents('hello.txt', "hello world\n");
file_put_contents('log.txt', "another\n", FILE_APPEND | LOCK_EX);
Streaming with a handle
PHP
$fh = fopen('big.log', 'r');
while (!feof($fh)) {
$line = fgets($fh);
process($line);
}
fclose($fh);
Modes
| Mode | Means |
|---|---|
r | Read; fail if missing. |
w | Write; truncates existing. |
a | Append; create if missing. |
x | Create-exclusive; fail if exists. |
r+ / w+ / a+ | Same but with read+write. |
b | Binary (recommended on Windows). |
Filesystem ops
| Function | Does |
|---|---|
file_exists($p) | True if path exists. |
is_file / is_dir / is_readable / is_writable | Predicate checks. |
copy / rename / unlink | Copy, rename, delete. |
mkdir($p, 0755, true) | Create directory (recursive). |
scandir / glob | List directory contents. |
filesize / filemtime | Size in bytes / modified time. |
realpath | Resolve to absolute path. |
Tip: Always use
__DIR__ + relative paths inside a project. Avoid ../ chains — pick a base like __DIR__ . '/../storage' and resolve from there.Example
Example
<?php
// Quick write + read
file_put_contents('hello.txt', "hello\n");
echo file_get_contents('hello.txt');
unlink('hello.txt');
Try it Yourself »
Exercise
Lock the file during write.
file_put_contents('log.txt', $line, FILE_APPEND |
);
Seven letters.
Discussion
Loading…