Lesson 13 — System Interaction
Working with Files
PHP can read from and write to files on the server's filesystem, useful for logging, simple data storage, and processing uploaded content.
Reading and Writing Files
PHP offers both a lower-level approach (fopen/fwrite/fclose) and simple one-line helper functions for common cases.
PHP — File handling
// Writing to a file
file_put_contents("log.txt", "New entry: " . date("Y-m-d H:i:s") . "\n", FILE_APPEND);
// Reading an entire file
$contents = file_get_contents("log.txt");
echo $contents;
Common Mistakes
- Forgetting FILE_APPEND when writing repeatedly to a log file, causing each write to overwrite the previous contents.
- Not checking whether a file exists (with file_exists()) before trying to read it, risking a warning or error.
- Leaving a file handle open (forgetting fclose()) when using the lower-level fopen approach.
- Writing user-controlled file paths without validation, which can open serious security vulnerabilities.
Professional Tip
For simple read/write needs, prefer file_get_contents() and file_put_contents() over the more verbose fopen/fread/fwrite/fclose sequence — they handle opening and closing the file automatically in a single call.
Your Turn
Write a script that appends a timestamped line to a log file every time it runs, and a second script that reads and displays the entire log.
Mini Quiz
What flag should you pass to file_put_contents() to add to a file instead of overwriting it?
Without
FILE_APPEND, file_put_contents() overwrites the entire file's contents by default on every call.