Table of Content
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.
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 can use the array_fill function in PHP when you must fill an array with one value. You may want…
PHP array_diff_key compares arrays and removes elements that share the same key. It checks only keys and keeps the values…
PHP introduced traits to solve a problem with code reuse. Before traits, developers used inheritance and interfaces to share functionality…
There are situations where you only need a specific number of rows returned. This is where the "LIMIT" clause in…
The PHP array_intersect function finds common values in arrays and returns matches as a new array. Understand the array_intersect in…
If you are working with PHP and need a way to confirm if something is indeed a file, the is_file function will…
User input can be unpredictable and dangerous. A simple form submission might carry malicious code or invalid data and lead…
PHP array_push lets you add one or more values to the end of an array. It appeared to make adding…
let's now dive into PHP comments—these simple but super important integral parts of PHP coding. You can think of comments…
You use integers (int) in PHP to count items, set page numbers, handle IDs, and manage loop counters. In this…