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

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

ModeMeans
rRead; fail if missing.
wWrite; truncates existing.
aAppend; create if missing.
xCreate-exclusive; fail if exists.
r+ / w+ / a+Same but with read+write.
bBinary (recommended on Windows).

Filesystem ops

FunctionDoes
file_exists($p)True if path exists.
is_file / is_dir / is_readable / is_writablePredicate checks.
copy / rename / unlinkCopy, rename, delete.
mkdir($p, 0755, true)Create directory (recursive).
scandir / globList directory contents.
filesize / filemtimeSize in bytes / modified time.
realpathResolve 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 | );

Test yourself

Q1. Wrap a write in LOCK_EX to…
Q2. "w" mode…
Q3. Highest-level shortcuts are…

Discussion

Loading…