Write and read a file with the same fopen

Hello,
I have read and write to a file but it does not work

Here is my php code that does not work to read the file

<?php
$file = 'text.txt';
$handle = fopen($file, 'w+');
fwrite($handle, "Text\
Text");
echo fread($handle, filesize($file)); // No display, why??
fclose($handle);

Can you tell me what causes this problem?
Thank you

Use this code:


$file = 'text.txt';
$handle = fopen($file, 'r+');
fputs($handle, "Text\
Text");
fclose($handle);

$contents = file_get_contents($file);
echo $contents;

if the the text file is gonna be very long a better way is to loop through each line with a while loop and fgets

Yes but why my code doesn’t work?

This is actually a common problem, the reason your code doesn’t work, is because of where the pointer is in the file. When using ‘w+’, it states to truncate the file and move the pointer to the beginning (good so far). Then you wrote a string of “Text
Text”, now the pointer is located AFTER your string. Now you are trying to read the file, but your pointer is already placed AFTER your string, so there is nothing to read.

So you need to move the pointer back to the beginning of the file by calling

rewind($handle);

Thank you very much for this explanation