Skip to content

PHP File Open/Read

PHP provides powerful functions for interacting with the server’s file system. This chapter covers the fundamental operations of opening, reading, and closing files using stream functions.

For simple operations like reading an entire file into a string or writing a string to a file, consider using the simpler file_get_contents() and file_put_contents() functions. However, for more control (e.g., reading line by line, working with large files, specific modes), the fopen(), fread(), fgets(), and fclose() functions are essential.

The fopen() function opens a file or URL and binds it to a stream resource. It provides fine-grained control over how the file is opened.

Syntax: fopen(string $filename, string $mode): resource|false

We will use a sample text file, webdictionary.txt, for examples:

AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language

The first parameter of fopen() is the file path, and the second specifies the access mode (e.g., read, write). fopen() returns a file pointer resource on success, or false on failure. Always check the return value.

Basic Example (Open for Reading):

<?php
declare(strict_types=1);
$filename = "webdictionary.txt";
$mode = "r"; // Open for reading only
// Attempt to open the file
$fileHandle = fopen($filename, $mode);
// Check if opening failed
if ($fileHandle === false) {
// Handle the error appropriately (log it, show a user-friendly message)
echo "Error: Unable to open file '{$filename}'!";
exit; // Exit script if the file is essential
} else {
echo "File '{$filename}' opened successfully.<br>";
// Proceed with file operations...
// Don't forget to close the file when done!
fclose($fileHandle);
echo "File closed.";
}
?>

Common File Modes:

ModeDescription
rRead only. Starts at the beginning of the file.
r+Read/Write. Starts at the beginning of the file.
wWrite only. Erases file contents or creates a new file. Starts at the beginning.
w+Read/Write. Erases file contents or creates a new file. Starts at the beginning.
aWrite only (Append). Preserves existing data. Starts at the end. Creates file if not exists.
a+Read/Write (Append). Preserves existing data. Starts at the end for writing, beginning for reading. Creates file if not exists.
xWrite only (Create exclusively). Creates a new file. Returns false and emits E_WARNING if file already exists.
x+Read/Write (Create exclusively). Creates a new file. Returns false and emits E_WARNING if file already exists.
cWrite only. Creates file if not exists. If it exists, does not erase, places pointer at beginning. (Less common than w or a)
c+Read/Write. Creates file if not exists. If it exists, does not erase, places pointer at beginning. (Less common than w+ or a+)

Note: Adding ‘b’ to the mode (e.g., ‘rb’, ‘wb’) is sometimes used for binary file operations, particularly on Windows, to prevent translation of newline characters. On Unix-like systems, ‘b’ is often ignored.

The fread() function reads a specified number of bytes from an open file pointer.

Syntax: fread(resource $handle, int $length): string|false

The first parameter is the file handle returned by fopen(), and the second is the maximum number of bytes to read.

Example: Read the entire contents of webdictionary.txt

<?php
declare(strict_types=1);
$filename = "webdictionary.txt";
// Check if file exists and is readable before opening
if (!is_readable($filename)) {
die("Error: File '{$filename}' does not exist or is not readable.");
}
$fileHandle = fopen($filename, "r");
if ($fileHandle === false) {
die("Error: Unable to open file '{$filename}'!");
}
// Get the file size to read the entire content
$fileSize = filesize($filename);
// Handle potential empty file or filesize error
if ($fileSize > 0) {
$content = fread($fileHandle, $fileSize);
if ($content === false) {
echo "Error reading from file.";
} else {
// Display content safely in HTML context
echo "<pre>" . htmlspecialchars($content, ENT_QUOTES, 'UTF-8') . "</pre>";
}
} elseif ($fileSize === 0) {
echo "File is empty.";
} else {
echo "Error getting file size.";
}
fclose($fileHandle);
?>

Note: Using filesize() with fread() is common for reading the whole file, but be cautious with very large files as this loads the entire content into memory. For large files, read in chunks within a loop.

The fclose() function closes an open file pointer, releasing the resource.

Syntax: fclose(resource $handle): bool

fclose() takes the file handle resource as its parameter. It returns true on success and false on failure.

<?php
$filename = "somefile.txt";
$fileHandle = fopen($filename, "a"); // Open for appending
if ($fileHandle) {
// ... perform operations like fwrite() ...
fwrite($fileHandle, "Appending a line.\n");
// Close the file handle
if (fclose($fileHandle)) {
echo "File '{$filename}' closed successfully.";
} else {
echo "Error closing file '{$filename}'.";
}
} else {
echo "Error opening file '{$filename}'.";
}
?>

The fgets() function reads a single line from an open file pointer.

Syntax: fgets(resource $handle, ?int $length = null): string|false

It reads up to length - 1 bytes, until a newline character (\n), or until the end of the file (EOF) is reached, whichever comes first. If length is omitted or null, it reads until the end of the line.

Example: Output the first line of webdictionary.txt

<?php
declare(strict_types=1);
$filename = "webdictionary.txt";
$fileHandle = fopen($filename, "r");
if ($fileHandle === false) {
die("Unable to open file!");
}
// Read the first line
$line = fgets($fileHandle);
if ($line === false) {
echo "Error reading line or end of file reached.";
} else {
echo "First line: " . htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
}
fclose($fileHandle);
?>

Important: After calling fgets(), the internal file pointer advances to the beginning of the next line.

The feof() function checks if the file pointer has reached the end of the file.

Syntax: feof(resource $handle): bool

feof() is essential when reading a file line by line or character by character in a loop, especially when the file length is unknown.

Example: Read webdictionary.txt line by line until EOF

<?php
declare(strict_types=1);
$filename = "webdictionary.txt";
$fileHandle = fopen($filename, "r");
if ($fileHandle === false) {
die("Unable to open file!");
}
echo "Reading file line by line:<br>";
// Loop until the end of the file is reached
while (!feof($fileHandle)) {
$line = fgets($fileHandle);
// Check if fgets actually returned a line (not false on error/EOF)
if ($line !== false) {
echo htmlspecialchars($line, ENT_QUOTES, 'UTF-8') . "<br>";
}
}
fclose($fileHandle);
?>

The fgetc() function reads a single character from an open file pointer.

Syntax: fgetc(resource $handle): string|false

It returns the character read, or false on EOF or error.

Example: Read webdictionary.txt character by character until EOF

<?php
declare(strict_types=1);
$filename = "webdictionary.txt";
$fileHandle = fopen($filename, "r");
if ($fileHandle === false) {
die("Unable to open file!");
}
echo "Reading file character by character:<br><pre>";
// Loop until the end of the file is reached
while (!feof($fileHandle)) {
$char = fgetc($fileHandle);
// Check if fgetc actually returned a character
if ($char !== false) {
echo htmlspecialchars($char, ENT_QUOTES, 'UTF-8');
}
}
echo "</pre>";
fclose($fileHandle);
?>

Note: Reading character by character is generally less efficient than reading line by line or in larger chunks.

Important: After calling fgetc(), the internal file pointer moves to the next character.

For a comprehensive reference of all filesystem functions, including writing (fwrite), seeking (fseek), directory operations, and more, consult the official PHP Manual:

https://www.php.net/manual/en/ref.filesystem.php

https://www.php.net/manual/en/ref.stream.php