PHP fread Function: How to Read Files in PHP

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 from fopen, which tells fread what 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") tells fread to 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 fopen to create a file pointer.
  • Reading Modes: Use fread to read either the entire file or specific chunks based on your needs.
  • Close Files: Always close your files with fclose to free up resources.

    Similar Reads

    PHP array_filter: How to Filter Array Values with Examples

    You can use array_filter in PHP to remove unwanted data from arrays. It works with a custom callback or default…

    File Handling in PHP

    File Handling in PHP is an important tool especially when you need to manage files such as reading, writing, or…

    PHP JSON Handling with json_encode & json_decode

    JSON is used in most of your web applications for dealing with data, and so, in a way, PHP JSON…

    PHP continue Statement: How to Skip Steps in Iteration

    The PHP continue statement skips the rest of the loop in the current cycle. It jumps to the next cycle…

    PHP Magic Constants: Simplify Your Code

    There are some tools known as "PHP magic constants" that will make your code a little more clever and versatile.…

    PHP array_unshift: How to Add Values to the Start of an Array

    PHP array_unshift helps you add new elements to appear before the existing ones. Understand the array_unshift function in PHP The…

    PHP str_repeat: How it Works with Examples

    PHP gives you many string tools. One of them is php str_repeat. This function repeats a texts as many times…

    PHP array_flip Function: How it Works with Examples

    PHP array_flip swaps keys with values. It works well when you need values as keys in fast lookups. What is…

    PHP is_readable: Check File Accessibility

    The PHP is_readable helps you validate file readability before any operation like read or include files. What Is PHP is_readable? The is_readable() function…

    PHP $_SERVER: Basics and Examples

    PHP $_SERVER is a superglobal. It’s a predefined variable containing information about your server, client, and request environment. As a…

    Previous Article

    PHP mail() Function: A Complete Guide

    Next Article

    PHP fwrite: How to Write Data to Files in PHP

    Write a Comment

    Leave a Comment

    Your email address will not be published. Required fields are marked *


    Subscribe to Get Updates

    Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
    No spam. Unsubscribe anytime.