Quick, whole-file operations:
$contents = file_get_contents('data.txt');
file_put_contents('data.txt', 'New content', FILE_APPEND);
$lines = file('data.txt', FILE_IGNORE_NEW_LINES); // returns an array of lines
Manual, line-by-line control with a file handle (better for very large files, since it doesn't load everything into memory at once):
$handle = fopen('data.txt', 'r');
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
}
Writing:
$handle = fopen('log.txt', 'a'); // 'a' = append; 'w' = overwrite; 'r' = read-only
fwrite($handle, "New log entry\n");
fclose($handle);
Checking and managing files:
file_exists('data.txt');
is_readable('data.txt'); is_writable('data.txt');
unlink('data.txt'); // delete
copy('a.txt', 'b.txt');
rename('old.txt', 'new.txt');
filesize('data.txt');
Working with directories: mkdir(), scandir(), is_dir(), and glob('*.txt') to find files matching a pattern. Always validate and sanitize any file path built from user input to prevent directory traversal attacks (e.g. ../../etc/passwd).