Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

1. File Inclusion & Handling

Lesson 21 of 36 in the free Web Based Programming notes on Siksha Sarovar, written by Rohit Jangra.

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.

  1. LOCK_SH: Shared lock (others can read, but not write).
  2. LOCK_EX: Exclusive lock (others cannot read or write).
  3. 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:

TermDefinition
FileA named resource on a storage device that holds data permanently
File PointerAn internal cursor that tracks the current read/write position within a file
BufferA temporary memory area used to hold data during file read/write operations
StreamA 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:

FunctionIf File is MissingExecution Continues?Best Used For
include()E_WARNING (notice)YesNon-essential files (ads, sidebar widgets)
require()E_COMPILE_ERROR (fatal)No — StopsEssential files (DB connection, config)
include_once()E_WARNINGYesInclude once, even if called multiple times
require_once()E_COMPILE_ERRORNo — StopsRequire 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.

ModeDescriptionFile Pointer Starts AtCreates File if Missing?Destroys Content?
rRead-onlyBeginningNoNo
wWrite-onlyBeginningYesYes (clears file)
aWrite-only (Append)EndYesNo
xCreate & WriteBeginningFails if existsN/A
r+Read & WriteBeginningNoNo
w+Read & WriteBeginningYesYes (clears file)
a+Read & Write (Append)EndYesNo

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.";
}