fread() Function in PHP
The fread() PHP function reads a specific number of bytes from an open file.
Syntax:
fread(resource $stream, int $length): string|false
- $stream: A file pointer (opened with
fopen()or similar). - $length: Number of bytes you want to read.
- Returns:
- The read data as a string.
falseif an error occurs.
Simple Example
Let's read 20 bytes from a text file:
<?php
// Open the file for reading
$handle = fopen("sample.txt", "r");
if ($handle) {
// Read 20 bytes
$content = fread($handle, 20);
echo $content;
// Close the file
fclose($handle);
} else {
echo "Error opening the file.";
}
?>
Here:
"sample.txt"is opened in read mode.fread()reads 20 bytes.- Always
fclose()after you're done!
Example: Read Full File
Usually, you don’t know the file size, so use filesize().
<?php
$handle = fopen("sample.txt", "r");
if ($handle) {
$content = fread($handle, filesize("sample.txt"));
echo $content;
fclose($handle);
} else {
echo "Error opening the file.";
}
?>
Here:
- We first get the total size of the file using
filesize("sample.txt"). - Then read the whole file in one go.
Important Points about fread()
- It reads binary-safe (can be used for images, PDFs, etc.).
- It does not automatically stop at end of line (
\n) — it reads exact bytes. - If the file pointer reaches EOF (End of File), it stops reading.
Real-world Example: Read an Image
<?php
$handle = fopen("photo.jpg", "rb"); // "rb" = read binary
if ($handle) {
$imageData = fread($handle, filesize("photo.jpg"));
fclose($handle);
// Now $imageData contains binary data of the image
}
?>
This is useful when you want to send image data through API or store it in a database.
Quick Tip
If you only need to read a full file easily, PHP provides file_get_contents(), which is simpler:
$content = file_get_contents("sample.txt");
But if you want partial reading, large files, or streaming, fread() is better.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
