Lesson 8 โข Intermediate
File Handling ๐
Read, write, and manage files on the server โ essential for logging, data persistence, file uploads, and CSV processing.
What You'll Learn in This Lesson
- โข Writing files with file_put_contents() and fopen()
- โข Reading files as strings, arrays, or line-by-line
- โข File modes: read, write, append, create
- โข Directory operations: create, list, scan
- โข CSV processing and file security best practices
file_put_contents() is placing a document in a folder (overwriting what was there). FILE_APPEND is adding a page to an existing document. file_get_contents() is pulling the entire document out to read. fopen() is opening the folder and reading one page at a time.1๏ธโฃ Quick vs Detailed File Access
| Approach | Functions | Best For |
|---|---|---|
| Quick (one-liner) | file_get/put_contents() | Small files, simple ops |
| Handle-based | fopen, fgets, fclose | Large files, streaming |
Try It: Reading & Writing Files
Write, read, and append to files using PHP's file functions
// PHP File Handling (simulated in JavaScript)
console.log("=== Writing Files ===");
console.log();
// file_put_contents โ the simplest way to write
console.log("file_put_contents('data.txt', 'Hello, World!');");
console.log(" โ Writes 'Hello, World!' to data.txt");
console.log(" โ Creates the file if it doesn't exist");
console.log(" โ OVERWRITES existing content!");
console.log();
// Append mode
console.log("file_put_contents('log.txt', 'New entry', FILE_APPEND);");
console.log(" โ Adds
...Try It: File Operations & Directories
Check file info, manage directories, and process CSV data
// File Operations & Directory Handling
console.log("=== File Information ===");
console.log();
// Simulated file stats
let stats = {
exists: true,
size: 2048,
modified: "2024-12-15 14:30:22",
permissions: "0644",
type: "file",
extension: "txt",
};
console.log("file_exists('data.txt') โ " + stats.exists);
console.log("filesize('data.txt') โ " + stats.size + " bytes");
console.log("filemtime('data.txt') โ " + stats.modified);
console.log("pathinfo('data.txt')['ex
...โ ๏ธ Common Mistakes
fclose($handle) or use file_put_contents() which handles this automatically.fopen('file.txt', 'w') truncates (erases) the file! Use 'a' for append.file_put_contents($file, $msg . PHP_EOL, FILE_APPEND | LOCK_EX) โ LOCK_EX prevents race conditions in concurrent writes.๐ Quick Reference โ File Handling
| Function | Purpose |
|---|---|
| file_get_contents() | Read entire file as string |
| file_put_contents() | Write string to file |
| file() | Read file into array of lines |
| fopen() / fclose() | Open/close file handle |
| fgets() / fwrite() | Read/write line by line |
| scandir() / mkdir() | List/create directories |
๐ Lesson Complete!
You've mastered PHP file handling! Next, learn how to process HTML forms and handle user input securely.
Sign up for free to track which lessons you've completed and get learning reminders.