How to Read File in PHP
In this tutorial, we will learn how to read a file in PHP. Reading data from a file is the most common operation when working with file handling in PHP. When you are building an application, handling CSV data, or processing logs, you will often need to read file content.
Reading a file is the process of opening a file and extracting its content or data for usage in your program. Reading files in PHP allows you to:
- Read text files that contain user information or product specifications.
- Retrieve data stored in .txt, .csv, .json, or other file formats.
- Process logs, configuration files, or settings files.
- Handle user uploads and stored documents.
- Import or export data for applications.
Functions to Read Files in PHP
PHP offers several built-in functions to read data from a file, each suited to different scenarios and requirements. Most of these functions work after a file has been opened using the fopen() function, while some can directly read the entire file without explicitly opening it. The most commonly used functions are:
- fread() – Reads a specified number of bytes from an open file.
- fgets() – Reads a single line from an open file.
- fgetc() – Reads a single character from an open file.
- file() – Reads an entire file into an array, with each line as an array element.
- file_get_contents() – Reads the whole file into a string.
How to Read a File Using fread() Function in PHP?
The most basic way to read a file in PHP is by using fread() function. The fread() function reads data from an open file. This function allows you to specify how many bytes you want to read from the file, which gives you control over reading either the whole file or just a part of it.
Basic Syntax
The basic syntax to define fread() function is as:
fread(resource $handle, int $length): stringParameters:
In the above syntax, the fread() function accepts two parameters:
- $handle → This parameter specifies the file pointer resource returned by the fopen() function.
- $length → This parameter defines the maximum number of bytes to read from the file. If you do not specify the $length parameter, PHP tries to read the entire file until EOF is reached.
Return Value:
- On success, the fread() function returns a string containing the data read from the file.
- On failure, it returns false.
- If the file pointer reaches the end of the file (EOF), it may return an empty string.
Example: Reading a File Using fread() Function
<?php
// Open the file in read mode.
$file = fopen("hello.txt", "r");
// Check if file opened successfully.
if ($file) {
// Get the file size.
$filesize = filesize("hello.txt");
// Read the file content.
$content = fread($file, $filesize);
// Display the content.
echo "File Content: \n" . $content;
// Close the file.
fclose($file);
} else {
echo "Failed to open the file.";
}
?>Output:
File Content:
Hello PHP!
This is an example of reading a file using fread() function.
Explanation:
- fopen(“hello.txt”, “r”) → Opens the file in read-only mode. You can specify the file using either a relative or absolute path. In this example, the file is placed in the same directory as the PHP script.
- filesize(“hello.txt”) → Returns the size of the file in bytes.
- fread($file, $filesize) → Reads the entire file content because the number of bytes to read is set to the file’s size.
- fclose($file) → Closes the file to free up system resources.
This method is best for reading small files completely.
How to Read File Line by Line in PHP?
Sometimes, you may need to read data from a file line by line. In this case, you can use the fgets() function. The fgets() function is a built-in PHP function that reads a single line from an open file until it reaches a newline character (\n) or the end of the file.
This function is especially useful when you want to process large files line by line instead of loading the entire file into memory.
Basic Syntax
The basic syntax to define fgets() function is as:
fgets(resource $handle, int $length = ?): string|falseParameters:
In the above syntax, the fgets () function takes two parameters:
- $handle → Specifies the file pointer resource returned by the fopen() function.
- $length → Defines the maximum number of bytes to read from the file. Reading stops when either a newline (\n) is found, the specified length is reached, or the end of the file is encountered.
Return Value:
- On success, the fgets() function returns the line read from the file, including the newline character (\n).
- On failure, it returns false.
- If the file pointer reaches the end of the file (EOF), it also returns false.
Example: Reading a File Line by Line
<?php
// Open the file in read mode.
$file = fopen("hello.txt", "r");
if ($file) {
// Read each line until the end of the file.
while (($line = fgets($file)) !== false) {
echo $line;
}
// Close the file.
fclose($file);
} else {
echo "Failed to open the file.";
}
?>Output:
Hello PHP!
Scientech Easy
PHP Tutorials
Explanation:
- fopen(“hello.txt”, “r”) → Opens the file in read-only mode.
- while (($line = fgets($file)) !== false) → Reads a new line from the file in each iteration. The loop continues until fgets() function reaches the end of the file (EOF) and returns false.
- echo $line → Prints each line on the browser with a line break.
- fclose($file) → Closes the file to free up the system resources.
Reading a File Line by Line Using feof() Function
There is an alternative way of reading a file line by line in PHP using the feof() function. This function checks whether or not the file pointer has reached the end of the file (EOF). We commonly use feof() with fgets() function in a loop to read files line by line when working with the data of unknown length.
Example: Using feof() Function
<?php
// Open the file in read mode.
$file = fopen("hello.txt", "r");
if ($file) {
// Keep reading until the file pointer reaches the end of the file.
while (!feof($file)) {
$line = fgets($file);
if ($line !== false) {
echo $line;
}
}
// Close the file.
fclose($file);
} else {
echo "Failed to open the file.";
}
?>Output:
Hello PHP!
Scientech Easy
PHP Tutorials
Explanation:
- fopen(“hello.txt”, “r”) → Opens the file in read-only mode.
- while (!feof($file)) → The loop runs until the file pointer reaches the end of the file.
- fgets($file) → Reads one line on each iteration.
- fclose($file) → Closes the file after reading.
Note:
If you use feof() function, it may sometimes read one extra empty line at the end of the file because the feof() function only returns true after trying to read beyond the end of the file. To handle this correctly, it’s good practice to check if fgets() returns false before processing the line as shown in the above code.
However, both methods (while (($line = fgets($file)) !== false) and while (!feof($file))) are valid, but the first method is cleaner and preferred.
How to Read a File Character by Character in PHP?
PHP provides a built-in fgetc() function that is used to read a single character from an open file. This function is especially useful when you want to process or parse a file character by character. For example, you might use it to count letters, detect special characters, or build a custom parser.
Basic Syntax
The basic form of the fgetc() function is as:
fgetc(resource $handle): string|falseParameter:
The fgetc() function takes one parameter:
- $handle → Specifies the file pointer resource returned by the fopen() function.
Return Value:
- On success, the fgetc() function returns the character read from the file.
- On failure, it returns false.
- If the file pointer reaches the end of the file (EOF), it also returns false.
Example: Reading a Character from File
<?php
$file = fopen("hello.txt", "r");
$str = fgetc($file);
echo $str;
fclose($file);
?>Output:
H
The above code displays the first character read from the “hello.txt” file.
Example: Reading a File Character by Character
<?php
// Open the file in read mode.
$file = fopen("hello.txt", "r");
if ($file) {
// Read character by character until EOF.
while (($char = fgetc($file)) !== false) {
echo $char . " ";
}
// Close the file
fclose($file);
} else {
echo "Failed to open the file.";
}
?>Output:
H e l l o P H P !
In this example, we have placed the fgetc() function inside a loop to read the file character by character until it reaches EOF.
How to Read Entire File in String?
PHP provides a built-in function named file_get_contents() that is used to read the entire file into a string. Unlike fread(), you don’t need to open the file using fopen(). The file_get_contents() function directly reads the contents in one step. That’s why this is a simple and efficient way to read files, including remote files via HTTP/HTTPS.
Basic Syntax
The general syntax to define file_get_contents() function is as:
string file_get_contents(string $filename, bool $use_include_path = false,
resource $context = null, int $offset = 0,
int $maxlen = null)Parameters:
The file_get_contents() function accepts five parameters:
- $filename → Name (path) of the file to read.
- $use_include_path → If this parameter is set to true, it also searches in the include path. Default is false.
- $context → This parameter defines a context resource created with stream_context_create().
- $offset → This parameter defines the position where to start reading in the file.
- $length → This parameter defines the number of bytes to read. If not specified, it reads until the end of the file.
Except $filename parameter, all the other parameters are optional.
Return Value:
- On success, the file_get_contents() function returns the file contents as a string.
- On failure, this function returns false.
Example: Reading Entire File
<?php
// Read the content of the file into a string.
$content = file_get_contents("hello.txt");
if ($content !== false) {
echo "File Content: \n";
echo $content;
} else {
echo "Failed to read the file.";
}
?>Output:
File Content:
Hello PHP!
In this example, we have read the full content of hello.txt file into a string using file_get_contents() function. If you want to check the output on the browser, use this code because it converts newlines \n into <br> tags so the output displays correctly in the browser.
echo "File Content: <br>"; echo nl2br($content); // nl2br converts newlines to <br> for display in browser.
How to Read File into Array?
To read the entire file into an array, use the file() function provided by PHP. The file() function is a built-in function that is used to read the entire file into an array. Each element of the array represents one line of the file, including the newline character (\n) at the end of each line.
The file() function is similar to file_get_contents() but returns an array instead of a string. This function is useful when you want to read files line by line but don’t want to manually use loops with fgets().
Basic Syntax
The basic syntax to define file() function is as:
array file(string $filename, int $flags = 0, resource $context = null)Parameters:
The file() function accepts three parameters:
- $filename → Name (path) of the file to read.
- $flags → This parameter controls how the file is read. However, this is an optional parameter.
- FILE_IGNORE_NEW_LINES → This flag removes the newline character at the end of each line.
- FILE_SKIP_EMPTY_LINES → This flag skips empty lines.
- $context → This parameter defines a context resource created with stream_context_create().
Return Value:
- On success, the file() function returns an array of lines.
- On failure, this function returns false.
Example: Read File into Array
<?php
// Read the file into an array.
$lines = file("hello.txt");
if ($lines !== false) {
echo "File Content: \n";
foreach ($lines as $line) {
echo $line;
}
} else {
echo "Failed to read the file.";
}
?>Output:
File Content:
Hello PHP!
PHP File Handling Tutorials
Note: Each line is stored as an element in the array.
Example: Using Flags
<?php
// Read file into array, ignore newlines and skip empty lines.
$lines = file("hello.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lines !== false) {
echo "File Content (Clean): \n";
foreach ($lines as $line) {
echo $line . "\n";
}
}
?>Output:
File Content (Clean):
Hello PHP!
PHP File Handling Tutorials
Contents of the file:
Hello PHP! PHP File Handling Tutorials
Key Points for Reading Files in PHP
- fopen() + fread() – Controlled reading
- fgets() – Line by line reading
- fgetc() – Character by character reading
- file_get_contents() – Reads entire file into a string
- file() – Reads entire file into array (lines)
- fgetcsv() – CSV-specific handling




