PHP’s file system allows you to read, write, and manage files and directories from within an application.
PHP has many ways to handle files (like the classic fopen, fwrite, fclose), but for most common tasks, there are “shortcut” functions that do all the heavy lifting in a single line. They are cleaner, more modern, and easier to read.
Reading files: file_get_contents
This is the star function for reading. It opens the file, reads all the content, stores it in a text variable (string), and automatically closes the file.
- Ideal use: Reading configuration files, HTML templates, or small/medium JSON files.
- Caution: It loads the entire file into RAM. Do not use it to read 500MB or gigabyte-sized files.
$file = 'note.txt';
if (file_exists($file)) {
// Reads all content and stores it in the variable
$content = file_get_contents($file);
echo "The content is: " . $content;
} else {
echo "The file does not exist.";
}file_get_contents() also supports URLs if allow_url_fopen is enabled. For consuming real HTTP services, it is usually preferable to use a client that allows configuring timeouts, headers, and error handling.
Writing files: file_put_contents
It is the exact opposite. It takes a string and saves it to a file. If the file does not exist, it attempts to create it.
By default, this function overwrites the file (erases the previous content). If you want to append content to the end (like in a log), you need to use “flags.”
$file = 'error_log.txt';
$message = "Error detected at " . date('H:i') . "\n";
// 1. Overwrite (Caution: erases previous content)
file_put_contents($file, $message);
// 2. Append to the end (Append Mode) - RECOMMENDED for logs
// LOCK_EX prevents two users from writing simultaneously and corrupting the file
file_put_contents($file, $message, FILE_APPEND | LOCK_EX);Other essential functions
These functions usually return false and emit a warning on failure. Checking the path reduces predictable errors, but you should also verify the return value because the file can change between the check and the operation.
| Function | Description | Example |
|---|---|---|
file_exists($path) | Checks if the file or folder exists. | if (file_exists('img.jpg')) |
is_writable($path) | Checks if you have permission to write. | if (is_writable('logs/')) |
unlink($path) | Deletes a file from the system. | unlink('temp.txt'); |
mkdir($path) | Creates a folder (directory). | mkdir('downloads'); |
Integrated example: a simple log system
Let’s combine what we have learned. A script that records a visit and displays the history.
$logFile = 'visits.txt';
// 1. Record the new visit (Write)
$newVisit = "Visit from IP 127.0.0.1 on " . date('d/m/Y H:i:s') . "\n";
file_put_contents($logFile, $newVisit, FILE_APPEND | LOCK_EX);
// 2. Display the history (Read)
try {
if (!file_exists($logFile)) {
throw new Exception("The log file has not been created yet.");
}
$history = file_get_contents($logFile);
// nl2br converts newlines (\n) into HTML <br> tags
echo "<h3>Visit History:</h3>";
echo nl2br($history);
} catch (Exception $e) {
echo "Notice: " . $e->getMessage();
}