PHP file handling allows us to create, open, read, write, append, and close files. It is useful for storing text, logs, and other information on a server.
PHP provides functions such as fopen(),
fread(), fwrite(),
fgets(), and fclose() to work
with files.
fopen() opens a file.fread() reads file contents.fwrite() writes data to a file.fclose() closes an open file.file_exists() checks whether a file exists.Create a file named sample.txt in the same
directory as your PHP file.
Example:
<?php
$file = "sample.txt";
if (file_exists($file)) {
echo "File exists.";
} else {
echo "File does not exist.";
}
?>
PHP file operations depend on file permissions and the directory in which the script runs.
The fopen() function opens a file using a
specified mode.
<?php
$file = fopen("sample.txt", "r");
if ($file !== false) {
echo "File opened successfully.";
fclose($file);
} else {
echo "Unable to open the file.";
}
?>
Output: File opened successfully.
| Mode | Meaning |
|---|---|
r |
Read only; file must exist. |
r+ |
Read and write; file must exist. |
w |
Write only; creates a file or truncates an existing file. |
w+ |
Read and write; creates or truncates a file. |
a |
Write at the end; creates the file if needed. |
a+ |
Read and append; creates the file if needed. |
x |
Create a new file for writing; fails if it exists. |
Always check whether fopen() succeeded before
using the returned file handle.
The fwrite() function writes data to an open
file. The w mode creates a new file if
necessary and removes the previous contents of an existing file.
<?php
$file = fopen("student.txt", "w");
if ($file !== false) {
fwrite($file, "Student Name: Rahul\n");
fwrite($file, "Course: PHP Programming\n");
fclose($file);
echo "Data written successfully.";
} else {
echo "Unable to open the file.";
}
?>
Output: Data written successfully.
Contents of student.txt:
Student Name: Rahul
Course: PHP Programming
The \n character adds a newline in the file.
On systems where exact newline formatting matters, use
the appropriate newline sequence.
The fread() function reads a specified number
of bytes from an open file.
<?php
$file = fopen("student.txt", "r");
if ($file !== false) {
$content = fread($file, filesize("student.txt"));
fclose($file);
echo nl2br(
htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')
);
} else {
echo "Unable to open the file.";
}
?>
This example assumes student.txt exists and
is not empty. For an empty file, filesize()
returns zero, so no bytes are read.
Displayed output:
Student Name: Rahul
Course: PHP Programming
fread() reads bytes, so take care when
handling large files or multibyte text.
The fgets() function reads one line at a time.
It is useful when a file contains multiple lines.
<?php
$file = fopen("student.txt", "r");
if ($file !== false) {
while (($line = fgets($file)) !== false) {
echo htmlspecialchars(
$line,
ENT_QUOTES | ENT_SUBSTITUTE,
'UTF-8'
) . "<br>";
}
fclose($file);
} else {
echo "Unable to open the file.";
}
?>
Output:
Student Name: Rahul
Course: PHP Programming
The loop stops when fgets() returns
false, such as at the end of the file.
The a mode writes new data at the end of a
file without removing its existing contents.
<?php
$file = fopen("student.txt", "a");
if ($file !== false) {
fwrite($file, "\nStudent Name: Priya");
fwrite($file, "\nCourse: Web Development");
fclose($file);
echo "New data appended successfully.";
} else {
echo "Unable to open the file.";
}
?>
Output: New data appended successfully.
Updated file contents:
Student Name: Rahul
Course: PHP Programming
Student Name: Priya
Course: Web Development
Run this example multiple times and the same information will be appended repeatedly. Add checks if duplicate entries must be prevented.
PHP provides several convenient file handling functions.
file_exists() checks whether a path exists.filesize() returns a file's size in bytes.file_get_contents() reads a file into a string.file_put_contents() writes a string to a file.unlink() deletes a file.is_file() checks whether a path refers to a regular file.<?php
$file = "student.txt";
if (is_file($file) && is_readable($file)) {
$content = file_get_contents($file);
if ($content !== false) {
echo nl2br(
htmlspecialchars(
$content,
ENT_QUOTES | ENT_SUBSTITUTE,
'UTF-8'
)
);
} else {
echo "Unable to read the file.";
}
} else {
echo "File is missing or not readable.";
}
?>
<?php
$result = file_put_contents(
"message.txt",
"Welcome to PHP file handling."
);
if ($result !== false) {
echo "File saved successfully.";
} else {
echo "Unable to save the file.";
}
?>
By default, file_put_contents() replaces
existing file contents. Use FILE_APPEND
to append instead.
The unlink() function deletes a file.
Use it carefully because deletion may be difficult to reverse.
<?php
$file = "old.txt";
if (is_file($file)) {
if (unlink($file)) {
echo "File deleted successfully.";
} else {
echo "Unable to delete the file.";
}
} else {
echo "File does not exist.";
}
?>
Never allow a user to supply an unrestricted file path for deletion. Restrict operations to an approved directory and validate the requested filename.
<?php
$file = fopen("missing.txt", "r");
if ($file === false) {
echo "Could not open the file.";
} else {
echo "File opened successfully.";
fclose($file);
}
?>
Output: Could not open the file.
In production applications, log technical details securely rather than exposing server paths or sensitive error information to visitors.
This example accepts a student name and course through a form and appends the details to a text file.
<?php
$message = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = trim($_POST["name"] ?? "");
$course = trim($_POST["course"] ?? "");
if ($name === "" || $course === "") {
$message = "Please enter both name and course.";
} else {
$record = "Name: " . $name
. " | Course: " . $course
. PHP_EOL;
$result = file_put_contents(
__DIR__ . "/students.txt",
$record,
FILE_APPEND | LOCK_EX
);
if ($result !== false) {
$message = "Student details saved successfully.";
} else {
$message = "Unable to save student details.";
}
}
}
?>
<form method="post">
<label for="name">Student Name:</label>
<input type="text" id="name" name="name" required>
<br><br>
<label for="course">Course Name:</label>
<input type="text" id="course" name="course" required>
<br><br>
<button type="submit">Save Student</button>
</form>
<?php if ($message !== ""): ?>
<p>
<?= htmlspecialchars(
$message,
ENT_QUOTES | ENT_SUBSTITUTE,
"UTF-8"
) ?>
</p>
<?php endif; ?>
Example file contents:
Name: Rahul | Course: PHP
Name: Priya | Course: Web Development
Important: This is a basic learning example. In a real application, validate input lengths, use an appropriate storage format, and keep writable files in a directory that is not publicly accessible. File locking helps coordinate concurrent writes but does not replace access controls.
1. Which function opens a file in PHP?
2. Which file mode appends data to the end of a file?
3. Which function deletes a file?