In some cases, you need to handle a lot of data or simply try to open a file, or read its contents. The fread function in PHP can help you manage file data, whether it’s in small chunks or all at once.
Table of Content
In the following sections, you will learn how to make fread work for you, with practical steps, examples, and tips for every stage. Let’s get into it!
What is the PHP “fread” Function?
The fread is a built-in function that lets you read specific amounts of data from a file. It is a tool that allows you to pull data in controlled, manageable chunks, especially useful when dealing with large files.
So, whether you are reading small text files or handling bigger data like JSON or logs.
let’s write its syntax:
fread(resource $handle, int $length): string|false
$handle: This is the file pointer resource. You get this fromfopen, which tellsfreadwhat file to read from.$length: This is the maximum number of bytes you want to read in one go.
Now, let’s break down how to open and read files and get this pointer resource.
Using “fopen” to Open a File and “fread” to Read Its Contents
Before you use fread, you need to open the file. PHP provides “fopen” for this purpose, which returns a file pointer required for fread to do its job.
Once your file is open, you can use fread to pull data from it. Here is an example:
$handle = fopen("example.txt", "r");
$contents = fread($handle, filesize("example.txt"));
fclose($handle);
echo $contents;
filesize("example.txt")tellsfreadto read the entire file size. This approach works well for small files.fclose($handle)is important to free up resources after you are done reading.
Now, let’s dive into a situation where you don’t need to read the whole file at once.
Reading Large Files in Chunks
Reading in chunks is a great way for larger files. So, when you use fread, you can read part of the file, process it, and then move to the next part. Here is how that looks in an example:
$handle = fopen("largefile.txt", "r");
while (!feof($handle)) {
$chunk = fread($handle, 1024); // Reads 1024 bytes (or 1KB) at a time
echo $chunk;
}
fclose($handle);
Take a look at the feof($handle) function, it checks if we have reached the end of the file. As long as there is data, fread will keep pulling in 1KB chunks. This helps us with big files and also avoids memory overload.
Anyway, we can do the same job but with a JSON file, let’s move on to the below section to see how it works.
Reading JSON Files in Chunks
PHP fread also handles JSON files. Let’s see another example of reading a JSON file in 4KB chunks:
$handle = fopen("data.json", "r");
$data = "";
while (!feof($handle)) {
$data .= fread($handle, 4096); // Reads 4KB at a time
}
fclose($handle);
$jsonArray = json_decode($data, true);
print_r($jsonArray);
Let’s see more examples.
PHP “fread” Examples
Here is an example for reading a small text file:
$handle = fopen("textfile.txt", "r");
echo fread($handle, filesize("textfile.txt"));
fclose($handle);
Reading a large log file in chunks:
$handle = fopen("logfile.log", "r");
while (!feof($handle)) {
// Read the file in 2KB chunks
echo fread($handle, 2048);
}
// Close the file after reading
fclose($handle);
If you’re handling JSON data, here’s a small example to make it feel more complete:
$handle = fopen("data.json", "r");
$data = "";
while (!feof($handle)) {
$data .= fread($handle, 4096); // Reads 4KB at a time
}
fclose($handle);
$jsonArray = json_decode($data, true);
print_r($jsonArray);
Let’s summarize it.
Wrapping Up
The PHP fread function gives us a reliable way to handle file reading, suitable for everything from small text files to larger datasets like logs or JSON. Here’s a quick recap:
- Syntax:
fread(resource $handle, int $length). - Opening Files: Start by opening files with
fopento create a file pointer. - Reading Modes: Use
freadto read either the entire file or specific chunks based on your needs. - Close Files: Always close your files with
fcloseto free up resources.
Similar Reads
You use integers (int) in PHP to count items, set page numbers, handle IDs, and manage loop counters. In this…
You can use the array_fill function in PHP when you must fill an array with one value. You may want…
Early PHP scripts often failed because of extra spaces or line breaks in strings. These issues came from user input…
actions, store settings, or even create log files for debugging. That’s where PHP fwrite comes in. It writes data to…
The OOP constructor initializes an object when it is created in PHP. Understand What a Constructor Is in PHP A…
PHP SimpleXML - invented for you to work with XML. Way leaner, quicker to get up. it's already integrated directly…
There are situations where you only need a specific number of rows returned. This is where the "LIMIT" clause in…
Variables in PHP are general elements used for data storage and other manipulations. Global variables belong to a particular category…
PHP array_flip swaps keys with values. It works well when you need values as keys in fast lookups. What is…
Deleting records in MongoDB is a common task. You might need to clear old data, remove outdated entries, or handle…