fread()

Last updated on

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.

Thank you for reading. Happy Coding!

Frequently Asked Questions (FAQs)

  • What is the syntax of 'fread' in PHP?

    The syntax of fread is:
    fread(resource $handle, int $length): string|false
  • How does 'fread' work in PHP?

    fread reads a specified number of bytes from an open file. You need a file pointer ($handle) created using fopen, and the length ($length) specifies how many bytes to read in one go.
  • How do I open a file for reading with 'fread'?

    To use fread, first open the file with fopen, which returns a file pointer that fread can use. Example:
    $handle = fopen("example.txt", "r");
  • How can I read the entire contents of a file in PHP?

    If the file is small, you can use fread with the entire file size:
    $handle = fopen("example.txt", "r");
    $contents = fread($handle, filesize("example.txt"));
    fclose($handle);
    echo $contents;
  • How do I read large files in chunks using 'fread'?

    To read large files without memory issues, use fread with a loop to read in chunks:
    $handle = fopen("largefile.txt", "r");
    while (!feof($handle)) {
        $chunk = fread($handle, 1024); // Reads 1KB at a time
        echo $chunk;
    }
    fclose($handle);
  • How do I check if I reached the end of a file in PHP?

    Use feof with fread in a loop to check for the end of the file:
    while (!feof($handle)) {
        $chunk = fread($handle, 1024);
    }
  • How can I read a JSON file with 'fread'?

    To read JSON, open the file, read in chunks, then decode it:
    $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);
  • Why should I close files after reading with 'fread'?

    Closing files with fclose releases resources and avoids potential memory issues. Example:
    fclose($handle);
  • How can I read only a specific number of bytes from a file?

    Specify the byte length in fread:
    $handle = fopen("example.txt", "r");
    $contents = fread($handle, 500); // Reads 500 bytes
    fclose($handle);
Share on: