Working with Files in PHP: Inclusion, Modes & Operations
Study Deep: The Race Condition (flock)
When multiple users try to write to the same file simultaneously, data corruption can occur. This is called a Race Condition.
Solution: Use flock() to lock the file before performing operations.
LOCK_SH: Shared lock (others can read, but not write).LOCK_EX: Exclusive lock (others cannot read or write).LOCK_UN: Release the lock.
1. What is File Handling?
File Handling is the ability of a program to create, read, write, append, and delete files stored on the server's file system. In PHP, this is essential for tasks like logging events, storing configuration data, generating reports, or managing user-uploaded content.
Key Terms:
| Term | Definition |
|---|---|
| File | A named resource on a storage device that holds data permanently |
| File Pointer | An internal cursor that tracks the current read/write position within a file |
| Buffer | A temporary memory area used to hold data during file read/write operations |
| Stream | A sequence of bytes flowing into or out of a program (e.g., reading from a file) |
| EOF (End-Of-File) | A marker that signals the end of a file has been reached |
2. File Inclusion
PHP allows you to insert the entire content of one PHP file into another file. This is a cornerstone of code organization — you write a header, footer, or database connection file once and include it everywhere.
The Four Inclusion Functions:
| Function | If File is Missing | Execution Continues? | Best Used For |
|---|---|---|---|
include() | E_WARNING (notice) | Yes | Non-essential files (ads, sidebar widgets) |
require() | E_COMPILE_ERROR (fatal) | No — Stops | Essential files (DB connection, config) |
include_once() | E_WARNING | Yes | Include once, even if called multiple times |
require_once() | E_COMPILE_ERROR | No — Stops | Require once, prevent duplicate includes |
// db_connection.php — Contains database credentials
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "myDatabase";
$conn = new mysqli($host, $user, $pass, $db);
?>
// index.php — Includes the connection file
<?php
require_once 'db_connection.php'; // STOPS if file is missing
include 'header.php'; // Continues even if header is absent
echo "Home Page";
include_once 'footer.php';
?>
Why use _once variants? If you have a large project with many includes, the same file (like a class definition) might accidentally be included twice, causing a "cannot redeclare class" fatal error. require_once and include_once prevent this.
3. File Open Modes (fopen)
Every file operation begins with fopen(), which opens a file and returns a file handle (resource). The mode argument determines exactly how the file is opened.
| Mode | Description | File Pointer Starts At | Creates File if Missing? | Destroys Content? |
|---|---|---|---|---|
r | Read-only | Beginning | No | No |
w | Write-only | Beginning | Yes | Yes (clears file) |
a | Write-only (Append) | End | Yes | No |
x | Create & Write | Beginning | Fails if exists | N/A |
r+ | Read & Write | Beginning | No | No |
w+ | Read & Write | Beginning | Yes | Yes (clears file) |
a+ | Read & Write (Append) | End | Yes | No |
4. Core File Operations
a) Opening a File:
$file = fopen("data.txt", "r"); // Open for reading
if (!$file) die("Error: Cannot open file!");
b) Reading from a File:
// Method 1: Read the entire file at once
$content = fread($file, filesize("data.txt"));
echo $content;
// Method 2: Read one line at a time (efficient for large files)
while (!feof($file)) {
echo fgets($file) . "<br>";
}
// Method 3: Read one character at a time
while (!feof($file)) {
echo fgetc($file);
}
c) Writing to a File:
$file = fopen("log.txt", "a"); // 'a' = append mode (doesn't erase data)
fwrite($file, "User logged in at " . date("Y-m-d H:i:s") . "
");
fclose($file);
echo "Log entry written!";
d) Shortcut Functions (No fopen needed):
// file_get_contents — Read entire file into a string
$text = file_get_contents("data.txt");
echo $text;
// file_put_contents — Write string to file (overwrites by default)
file_put_contents("data.txt", "New content here.");
// file_put_contents with FILE_APPEND flag — Appends instead
file_put_contents("log.txt", "New log entry
", FILE_APPEND);
e) Closing a File (Always close!): Not closing a file can lead to data loss or file corruption.
fclose($file); // Always close when done
5. Checking File Existence before Operations
Always verify a file exists before trying to read it to prevent warnings and errors.
$filename = "report.txt";
if (file_exists($filename)) {
$content = file_get_contents($filename);
echo $content;
} else {
echo "Error: File '$filename' does not exist.";
}