Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php fread file function

Tags:

file

php

I wrote the below code to output the contents of a file twice. But it only did it once. Why is that?

The text file contents are as follows:

My name is Sam. Sam I am.
My name is Chris and Chris I am.
The brown fox jumped over the fence.

The code is as follows:

<?php
$file = "files/info.txt";
$handle = fopen($file, "rb");
echo fread($handle, filesize($file));
echo fread($handle, filesize($file));
?>

The output:

"My name is Sam. Sam I am. My name is Chris and Chris I am. The brown fox jumped over the fence."
like image 290
Robert Rocha Avatar asked Jan 21 '26 20:01

Robert Rocha


2 Answers

Invoking fread() "uses up" the file and in order to fread() it again you have to move the reading pointer back to the beginning of the file using rewind($handle)

like image 125
Dane Hillard Avatar answered Jan 24 '26 10:01

Dane Hillard


For the first fread(), file pointer moves to end of the file, so second time nothing printed. execute the bellow code , you will come to know.

<?php
$file = "info.txt";
$handle = fopen($file, "rb");
echo fread($handle, filesize($file)-10);
print "-----";
echo fread($handle, filesize($file));
?>
like image 38
Soumitra Avatar answered Jan 24 '26 11:01

Soumitra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!