Current Location: Home> Latest Articles> How to Use ftell and fread Together to Read Data from a Specific Position in a File?

How to Use ftell and fread Together to Read Data from a Specific Position in a File?

gitbox 2025-09-11

<?php
// Main content starts
echo "

How to Use ftell and fread Together to Read Data from a Specific Position in a File?

";

echo "

In PHP, when handling files, sometimes we need to read data from a specific position in the file. The ftell() and fread() functions can work well together to accomplish this task.

"
;

echo "

1. ftell() Function

"
;
echo "

The ftell() function returns the current position of the file pointer (in bytes). With ftell(), we can determine where we are in the file during reading.

"
;

echo "

2. fread() Function

"
;
echo "

The fread() function is used to read a specified length of data from a file. Its basic usage is as follows:

"
;
echo "
<br>
fread(resource $handle, int $length);<br>
"
;
echo "

Here, $handle is the file resource, and $length is the number of bytes to read.

"
;

echo "

3. Example of Using Them Together

"
;
echo "

Suppose we have a text file called example.txt, and we want to read 20 bytes starting from the 10th byte:

"
;
echo "
// Check the current position
\$position = ftell(\$handle);
echo 'Current pointer position: ' . \$position . \"\\n\";

// Read 20 bytes
\$data = fread(\$handle, 20);
echo 'Data read: ' . \$data;

fclose(\$handle);

} else {
echo 'Unable to open file';
}
";

echo "

In this example:

"
;
echo "

  • Use fseek(\$handle, 10) to move the file pointer to the 10th byte.
  • Use ftell(\$handle) to confirm the current pointer position.
  • Use fread(\$handle, 20) to read 20 bytes of data from the current pointer position.
"
;

echo "

4. Summary

"
;
echo "

By combining fseek(), ftell(), and fread(), we can precisely read data from any position in a file. This is especially useful when working with large files or when specific content needs to be skipped.

"
;
?>