fread()
Function in PHP
The fread()
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.
false
if 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.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.