0
0
PhpHow-ToBeginner · 3 min read

How to Use fread in PHP: Syntax, Example, and Tips

In PHP, fread reads a specified number of bytes from an open file pointer. You first open a file with fopen, then use fread to read data, and finally close the file with fclose.
📐

Syntax

The fread function requires two arguments: the file pointer and the number of bytes to read. It returns the read data as a string.

  • resource $handle: The file pointer returned by fopen.
  • int $length: Number of bytes to read from the file.
php
string fread(resource $handle, int $length);
💻

Example

This example opens a text file, reads the first 20 bytes, prints the content, and then closes the file.

php
<?php
$filename = 'example.txt';
// Open the file for reading
$file = fopen($filename, 'r');
if ($file) {
    // Read 20 bytes from the file
    $content = fread($file, 20);
    // Print the read content
    echo $content;
    // Close the file
    fclose($file);
} else {
    echo 'Failed to open the file.';
}
?>
Output
Hello, this is a test
⚠️

Common Pitfalls

  • Not opening the file before calling fread causes errors.
  • Reading more bytes than the file size returns fewer bytes without error.
  • Forgetting to close the file with fclose can lock resources.
  • Using fread on a closed or invalid file pointer returns false.
php
<?php
// Wrong: fread without fopen
$content = fread(null, 10); // Causes warning

// Right: fopen before fread
$file = fopen('example.txt', 'r');
$content = fread($file, 10);
fclose($file);
?>
📊

Quick Reference

FunctionDescription
fopenOpen a file and return its pointer
freadRead a specified number of bytes from an open file
fcloseClose an open file pointer

Key Takeaways

Always open a file with fopen before using fread.
Specify the number of bytes to read; fread returns fewer bytes if the file is smaller.
Close the file with fclose to free system resources.
fread returns a string with the read data or false on failure.
Check if fopen succeeded before calling fread to avoid errors.