File Operations in PHP

From the PHP cheat sheet · File Handling · verified Jul 2026

File Operations

Working with files and directories

php
// Read file
$content = file_get_contents('file.txt');
$lines = file('file.txt', FILE_IGNORE_NEW_LINES);

// Write file
file_put_contents('file.txt', $data);
file_put_contents('log.txt', $data, FILE_APPEND);

// File info
if (file_exists($file)) {
    $size = filesize($file);
    $modified = filemtime($file);
}

// Directory operations
$files = scandir($directory);
mkdir('new_directory', 0755, true);
💡 Use file_get_contents for simple reads, handles for large files
⚡ Always check file_exists() before operations
📌 Use LOCK_EX flag to prevent race conditions
🔥 Set proper permissions (0755 for dirs, 0644 for files)
Back to the full PHP cheat sheet