Topics Error Handling & File System File System Operations
intermediate 12 min read

File System Operations

Reading/writing files, directories, file permissions, and streams.

File Operations

// Read entire file
\$content = file_get_contents('file.txt');

// Write to file
file_put_contents('file.txt', \$content);

// Read line by line
\$handle = fopen('file.txt', 'r');
while ((\$line = fgets(\$handle)) !== false) {
echo \$line;
}
fclose(\$handle);

// CSV
\$data = array_map('str_getcsv', file('data.csv'));

Directory Operations

mkdir('dir', 0755, true); // recursive
rmdir('dir'); // must be empty
scandir('dir'); // list files
is_file() / is_dir() / file_exists()
unlink('file.txt'); // delete file
copy('src', 'dst');
rename('old', 'new');

Streams

// PHP stream wrappers
\$content = file_get_contents('php://input');
file_put_contents('php://stdout', \$content);

Examples

<?php
$dir = './test_dir';
if (!is_dir($dir)) mkdir($dir, 0755, true);
file_put_contents($dir . '/hello.txt', 'Hello World');
echo file_get_contents($dir . '/hello.txt');
// Cleanup
unlink($dir . '/hello.txt');
rmdir($dir);

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.